var ubication = "http://sigueloya.com/sms_contact/";
  
var currentDate = new Date();
var hour = currentDate.getHours();
var minute = currentDate.getMinutes();
var segond = currentDate.getSeconds();
var day = currentDate.getDate();
var month = currentDate.getMonth() + 1; 
var year = currentDate.getFullYear();
var hour_default_ini = "00:00:00"; 
var hour_default_fin = "23:59:59"; 
var daycurrent = ""+day;
var monthcurrent = ""+month;   

if(monthcurrent.length==1){
	monthcurrent = "0"+month;
}
  
if(daycurrent.length==1){            
	daycurrent = "0"+day;
}

var datenow = year + "-" + monthcurrent + "-" + daycurrent;

var db;
var numberPhone;
var id_device;
var convalue;
var company;

var phone_fix;
var phone_cel;
var address;
var position_contact;
var date_quote;
var hour_qoute;
var hour_qoute_fin;
var date_quote_fin;
var new_dateini;
var new_date_final;
var obs_quot;

var ctrl_new_to_presave = 0;
var ID_contact;
var ID_Company;

var ID_CON;

var f_ini2;
var f_fin2;
var my_obs;

var fi_data_am;
var fi_data_pm;
var quotes;

var count_call_exist = 0;

var name_compsny_display = "";

var id_date2;

var id_quote_schedule;
var chk_status_reu_efect = 0;
var chk_status_sales = 1;
var my_idSchedule;

var idSales;
var idContactSales;

var d1;
var d2;

var roleUser;
var nameu_co;
var enterprise_ID;

var username;
 
var quotedaycurrent1;
var quotedaycurrent2;

var watchID = null;
var controller_count_;

var version_contact_local;
var version_company_local;
var conn;

var status_pass_to_sale = 0;
var version_app;
var person_natural = 1;
var person_judirica = 0;
var address_schedule = ""; 
var control_display_quot;
var data_last_day_call;
var id_server_sale_assigned;
var last_address_meeting="";
var status_proposal = 0;
var date_meeting_selected = '';


function init() {
    document.addEventListener("deviceready", onDeviceReady, false);
    db = window.openDatabase("SiguelosDB", "1.0", "Database of Siguelos",
            200000);
}

function executeSql(sql, args, successHandler, errorHandler) {
    console.log("executeSql:" + sql + " args:" + args);
    db.transaction(function(transaction) {
        transaction.executeSql(sql, args, successHandler, errorHandler);
    });
}
 
function onDeviceReady() {
    executeSql('CREATE TABLE IF NOT EXISTS contact (id integer not null primary key autoincrement, id_server integer, company_id integer, name_company text,  name text, role text, phone1 text, phone2 text, address text, creation_date DATETIME, creation_user_name text, enterprise_id integer, sincr integer)', [], CreateTableSuccess, CreateTableError);
    executeSql('CREATE TABLE IF NOT EXISTS company (id integer not null primary key autoincrement, id_server integer, name text, address text, creation_date DATETIME, create_user_name text, enterprise_id integer, sincr integer)', [], CreateTableSuccess, CreateTableError);
    executeSql('CREATE TABLE IF NOT EXISTS sales (id integer not null primary key autoincrement, id_contact integer, value_sale integer, date_sale DATETIME, creation_date_sale DATETIME, obs text, company_id integer, enterprise_id integer, sincr integer)', [], CreateTableSuccess, CreateTableError);
    executeSql('CREATE TABLE IF NOT EXISTS controlapp (id integer not null primary key autoincrement, code_activ integer, status_activ integer, sms_processing integer, phone text, role integer, nameuserco text, version_company integer, version_contact integer, enterprise_id integer, version_app integer)', [], CreateTableSuccess, CreateTableError);
    executeSql('CREATE TABLE IF NOT EXISTS schedule (id integer not null primary key autoincrement, id_contact integer, creation_date DATE, date_reu_ini DATETIME, date_reu_fin DATETIME, reu_efec integer, obs text, company_id integer, enterprise_id integer, sincr integer, address text, meeting_re integer)', [], CreateTableSuccess, CreateTableError);
    executeSql('CREATE TABLE IF NOT EXISTS calldia (id integer not null primary key autoincrement, date_noti DATETIME, dateini DATETIME, cntcall integer, datacompara DATATIME, sincr integer)', [], CreateTableSuccess, CreateTableError);
    executeSql('CREATE TABLE IF NOT EXISTS assigned (id integer not null primary key autoincrement, id_server integer, id_seller integer, type_assigned integer, amount integer, start_period DATE, finish_period DATE, total_reported integer, date_reported DATETIME)', [], CreateTableSuccess, CreateTableError);    
    executeSql('CREATE TABLE IF NOT EXISTS auxdelete (id integer not null primary key autoincrement, id_app integer)', [], CreateTableSuccess, CreateTableError);    
	  
    
    function confirmDialog(text, callback) { 
        var popupDialogId = 'popupDialog';
        $('<div data-role="popup" id="' + popupDialogId + '" data-confirmed="no" data-transition="pop" data-overlay-theme="b" data-theme="b" data-dismissible="false" style="max-width:500px;"> \
                            <div data-role="header" data-theme="a">\
                                <h1>Confirmar</h1>\
                            </div>\
                            <div role="main" class="ui-content" align="center">\
                                <h3 class="ui-title"> <img id="theImg" src="img/int.png" />' + text + '</h3>\
                                <a href="#" class="ui-btn ui-corner-all ui-shadow ui-btn-inline ui-btn-b optionConfirm" data-rel="back">Aceptar</a>\
                                <a href="#" class="ui-btn ui-corner-all ui-shadow ui-btn-inline ui-btn-b optionCancel" data-rel="back" data-transition="flow">Cancelar</a>\
                            </div>\
                        </div>')
            .appendTo($.mobile.pageContainer);
        var popupDialogObj = $('#' + popupDialogId);
        popupDialogObj.trigger('create');
        popupDialogObj.popup({
            afterclose: function (event, ui) {
                popupDialogObj.find(".optionConfirm").first().off('click');
                var isConfirmed = popupDialogObj.attr('data-confirmed') === 'yes' ? true : false;
                $(event.target).remove();
                if (isConfirmed && callback) {
                    callback();
                }
            }
        }); 
        popupDialogObj.popup('open');
        popupDialogObj.find(".optionConfirm").first().on('click', function () {
            popupDialogObj.attr('data-confirmed', 'yes');
        });
    }
    
   
           
     
    function Dialog(text, callback, icon) {
            var popupDialogId = 'popupDialog';
            $('<div data-role="popup" id="' + popupDialogId + '" data-confirmed="no" data-transition="pop" data-overlay-theme="a" data-theme="b" data-dismissible="false" style="max-width:500px;"> \
                                <div data-role="header" data-theme="a">\
                                    <h1>Advertencia</h1>\
                                </div>\
                                <div role="main" class="ui-content" align="center">\
                                    <h3 class="ui-title"> <img id="theImg" src="img/'+icon+'.png" />' + text + '</h3>\
                                    <a href="#" class="ui-btn ui-corner-all ui-shadow ui-btn-inline ui-btn-b optionCancel" data-rel="back"  data-transition="flow">Aceptar</a>\
                                </div>\
              </div>')
            .appendTo($.mobile.pageContainer);
                    var popupDialogObj = $('#' + popupDialogId);
                    popupDialogObj.trigger('create');
                    popupDialogObj.popup({
                        afterclose: function (event, ui) {
                            popupDialogObj.find(".optionConfirm").first().off('click');
                            var isConfirmed = popupDialogObj.attr('data-confirmed') === 'yes' ? true : false;
                            $(event.target).remove();
                            if (isConfirmed && callback) {
                                callback();
                            }
                        }
                    });
                    popupDialogObj.popup('open');
                    popupDialogObj.find(".optionConfirm").first().on('click', function () {
                        popupDialogObj.attr('data-confirmed', 'yes');
                    });
                }
    
    
   
    function get_count_call_to_date(date_start, date_finish, amount_assigned){
    	executeSql("SELECT SUM(cntcall) AS llamadas from calldia WHERE date(datacompara) BETWEEN ? AND ?", [date_start, date_finish], function sucessname (tx, results) {	                
    		var len = results.rows.length;    		
    		if (len > 0) {
    			for (var i = 0; i < len; i++) {
    				var count_call = results.rows.item(i).llamadas;	
    				console.log("Llamadas hechas "+count_call+" Fecha inicio asignada "+date_start+" Fecha final asignada "+date_finish);
    				view_average_call(count_call, date_start, date_finish, amount_assigned);
    			}
    		}
    		else{
    			console.log("No hay llamadas que pintar en este rango de fechas");
    		}
    }, errorCB);  
    }  
      
      
    $('#go_view_assigned').click(function() {
    	view_assigned_call();
    	view_assigned_meeting();
    	view_assigned_proposal();
    	view_assigned_sales();
    });
     
    function view_assigned_call(){
    	executeSql("SELECT * from assigned WHERE type_assigned = ? AND date('"+datenow+"') BETWEEN start_period AND finish_period", [1], function sucessname (tx, results) {	                
    		var len = results.rows.length; 
    		console.log("Registro de llamadas Asignadas Obtenidos => "+len);
    		if (len > 0) {   
    			for (var i = 0; i < len; i++) {
    				var type = results.rows.item(i).type_assigned;
    				var data_sta = results.rows.item(i).start_period;
    				var data_final = results.rows.item(i).finish_period;
    				var count_call_assigned = results.rows.item(i).amount;
    				
    				get_count_call_to_date(data_sta, data_final, count_call_assigned);
    			}
    		}
    		else{
    			console.log("No hay registro de llamadas asignadas que mostrar");
    		}
    }, errorCB);
    }
      
      
    function view_assigned_meeting(){
    	executeSql("SELECT * from assigned WHERE type_assigned = ? AND date('"+datenow+"') BETWEEN start_period AND finish_period", [3], function sucessname (tx, results) {	                
    		var len = results.rows.length; 
    		console.log("Registro de Reuniones asignadas Obtenidas => "+len);
    		if (len > 0) {
    			for (var i = 0; i < len; i++) {
    				var type = results.rows.item(i).type_assigned;
    				var data_sta = results.rows.item(i).start_period;
    				var data_final = results.rows.item(i).finish_period;
    				var count_meeting_assigned = results.rows.item(i).amount;
    				
    				get_count_meeting_to_date(data_sta, data_final, count_meeting_assigned);
    			} 
    		}
    		else{
    			console.log("No hay registro de reuniones asignadas que mostrar");
    		}
    }, errorCB); 
    }
      
    
    function view_assigned_proposal(){
    	executeSql("SELECT * from assigned WHERE type_assigned = ? AND date('"+datenow+"') BETWEEN start_period AND finish_period", [4], function sucessname (tx, results) {	                
    		var len = results.rows.length; 
    		console.log("Registro de propuestas asignadas Obtenidas => "+len);
    		if (len > 0) {
    			for (var i = 0; i < len; i++) {
    				var type = results.rows.item(i).type_assigned;
    				var data_sta = results.rows.item(i).start_period;
    				var data_final = results.rows.item(i).finish_period;
    				var count_meeting_assigned = results.rows.item(i).amount;
    				
    				get_count_proposal_to_date(data_sta, data_final, count_meeting_assigned);
    			}
    		}
    		else{
    			console.log("No hay registro de reuniones asignadas que mostrar");
    		}
    }, errorCB);
    }
    
    
    function view_assigned_sales(){
    	executeSql("SELECT * from assigned WHERE type_assigned = ? AND date('"+datenow+"') BETWEEN start_period AND finish_period", [2], function sucessname (tx, results) {	                
    		var len = results.rows.length; 
    		console.log("Registro de ventas asignadas Obtenidas => "+len);
    		if (len > 0) {
    			for (var i = 0; i < len; i++) {
    				var type = results.rows.item(i).type_assigned;
    				var data_sta = results.rows.item(i).start_period;
    				var data_final = results.rows.item(i).finish_period;
    				var count_meeting_assigned = results.rows.item(i).amount;
    				
    				get_count_sales_to_date(data_sta, data_final, count_meeting_assigned);
    			}
    		}
    		else{
    			console.log("No hay registro de reuniones asignadas que mostrar");
    		}
    }, errorCB);
    }
    

    
   
    
    
    function get_count_meeting_to_date(date_start, date_finish, amount_assigned){
    	executeSql("SELECT COUNT(id) AS reuniones from schedule WHERE DATE(creation_date) BETWEEN ? AND ?", [date_start, date_finish], function sucessname (tx, results) {	                
    		var len = results.rows.length;    		
    		if (len > 0) {
    			for (var i = 0; i < len; i++) {
    				var count_meeting = results.rows.item(i).reuniones;
    				console.log("Reuniones hechas "+count_meeting+" Fecha inicio asignada "+date_start+" Fecha final asignada "+date_finish);
    				view_average_meeting(count_meeting, date_start, date_finish, amount_assigned);
    			}
    		}  
    		else{
    			console.log("No hay reuniones que pintar en este rango de fechas");
    		} 
    }, errorCB);
    }  
     
    function get_count_proposal_to_date(date_start, date_finish, amount_assigned){
    	executeSql("SELECT SUM(reu_efec) AS propuestas from schedule WHERE reu_efec = ? AND creation_date BETWEEN ? AND ?", [1, date_start, date_finish], function sucessname (tx, results) {	                
    		var len = results.rows.length;    		 
    		if (len > 0) {
    			for (var i = 0; i < len; i++) {
    				var count_propo = results.rows.item(i).propuestas;	   
    				view_average_proposal(count_propo, date_start, date_finish, amount_assigned);
    			}
    		}
    		else{
    			console.log("No hay propuestas que pintar en este rango de fechas");
    		}
    }, errorCB);
    } 
    
    
    function get_count_sales_to_date(date_start, date_finish, amount_assigned){
    	executeSql("SELECT SUM(value_sale) AS ventas from sales WHERE creation_date_sale BETWEEN ? AND ?", [date_start, date_finish], function sucessname (tx, results) {	                
    		var len = results.rows.length;
    		
    		if (len > 0) {
    			for (var i = 0; i < len; i++) {
    				var count_sale = results.rows.item(i).ventas;	    				
    				view_average_sale(count_sale, date_start, date_finish, amount_assigned);
    			}
    		}
    		else{
    			console.log("No hay propuestas que pintar en este rango de fechas");
    		}
    }, errorCB);
    } 
     
  
    
    //pinta el grafico de promedio de llamadas
    function view_average_call(value, date_ini, date_fin, amount_assigned){
    	var poncen = (value / amount_assigned) * 100;    
    	var temp = ""+poncen;
    	var new_value = temp.substring(0, 2);
    	//etiquetas para llamadas
    	document.getElementById('period_call').innerHTML = "Llamadas: "+date_ini+" a: "+date_fin;
    	document.getElementById('cant_call').innerHTML   = "Cantidad : "+amount_assigned;
    	
    	$( '#circle_call' ).progressCircle();
		$( '#circle_call' ).progressCircle({
			nPercent        : new_value,
			thickness       : 4,
			circleSize      : 100
		});	 
    }
    
  //pinta el grafico de promedio de reuniones
    function view_average_meeting(value, date_ini, date_fin, amount_assigned){
    	var poncen = (value / amount_assigned) * 100;
    	var temp = ""+poncen;
    	var new_value = temp.substring(0, 2);
    	//etiquetas para reuniones
    	document.getElementById('period_meeting').innerHTML = "Reuniones: "+date_ini+" a: "+date_fin;
    	document.getElementById('cant_meeting').innerHTML   = "Cantidad : "+amount_assigned;
    	
    	$( '#circle_meeting' ).progressCircle();
		$( '#circle_meeting' ).progressCircle({
			nPercent        : new_value,
			thickness       : 4,
			circleSize      : 100
		});	 
    }
    
  //pinta el grafico de promedio de propuestas
    function view_average_proposal(value, date_ini, date_fin, amount_assigned){
    	var poncen = (value / amount_assigned) * 100; 
    	var temp = ""+poncen;
    	var new_value = temp.substring(0, 2);
    	//etiquetas para reuniones
    	document.getElementById('period_proposal').innerHTML = "Propuestas: "+date_ini+" a: "+date_fin;
    	document.getElementById('cant_proposal').innerHTML   = "Cantidad : "+amount_assigned;
    	
    	$( '#circle_proposal' ).progressCircle();
		$( '#circle_proposal' ).progressCircle({
			nPercent        : new_value,
			thickness       : 4,
			circleSize      : 100
		});	 
    }
    
    
  //pinta el grafico de promedio de ventas
    function view_average_sale(value, date_ini, date_fin, amount_assigned){
    	var poncen = (value / amount_assigned) * 100;
    	var temp = ""+poncen;
    	var new_value = temp.substring(0, 2);
    	//etiquetas para reuniones
    	document.getElementById('period_sale').innerHTML = "Ventas: "+date_ini+" a: "+date_fin;
    	document.getElementById('cant_sale').innerHTML   = "Cantidad : "+amount_assigned;
    	
    	$( '#circle_sale' ).progressCircle();
		$( '#circle_sale' ).progressCircle({
			nPercent        : new_value,
			thickness       : 4,
			circleSize      : 100
		});	 
    }
    
      
    function get_sales_assigned(){ 
    	$.ajax({
            type: "POST",
            url: ubication + "get_sales_assigned.php",
            data: ({
                name_seller: nameu_co, 
                enterp_id: enterprise_ID,
            }),
            async: true, 
            success: function(datos) {        	
            	var dataJson = eval(datos);
               for (var i in dataJson) {
            	    var id_server = dataJson[i].id_server;
                	var my_amount = dataJson[i].my_amount;                	
                	var my_type = dataJson[i].my_type;
                	var id_seller = dataJson[i].idseller;
                	var start_date = dataJson[i].start_date;
                	var end_date = dataJson[i].end_date;
                	var total_reported = dataJson[i].total_rep;
                	var date_reported = dataJson[i].date_rep;
                	
                		if(my_amount != 'Error'){
                			console.log("Metas obtenidas correctamente para el vendedor TYPE =>"+my_type+" Cantidad =>"+my_amount);
                				update_sales_assigned(id_server, id_seller, my_amount, my_type, start_date, end_date, total_reported, date_reported);
                		}
                }                    
            },
            error: function(obj, error, objError) {
                console.error("Error accediendo a la pagina getname_seller.php");
            }
        });
    }
    
     
function update_sales_assigned(id_server, id_seller, value, type, start_date, end_date, total_reported, date_reported){
	
	executeSql("select * FROM assigned WHERE id_server = ?", [id_server], function sucessname (tx, results) {	        
		var len = results.rows.length;
		if (len > 0) {
			executeSql("UPDATE assigned SET id_server = ?, id_seller = ?, type_assigned = ?, amount = ?, start_period = ?, finish_period = ?, total_reported = ?, date_reported = ? WHERE id_server = ?", 
[id_server, id_seller, type, value, start_date, end_date, total_reported, date_reported, id_server], function sucessname (tx, results) {	        
		    console.log("Metas del vendedor actualizadas correctamente"); 		    
			}, errorCB);
		}else{
			executeSql("INSERT INTO assigned (id_server, id_seller, type_assigned, amount, start_period, finish_period, total_reported, date_reported) VALUES(?,?,?,?,?,?,?,?);", [id_server, id_seller, value, type, start_date, end_date, total_reported, date_reported], function success (tx, results) {	        
			console.log("Metas del agregada correctamente"); 
			}, errorCB);
		}  
	}, errorCB);	
}
 
//envia los reportes finales a la central
function get_report(){
	executeSql("SELECT id_server, amount, type_assigned, start_period, finish_period FROM assigned WHERE date('now') > finish_period", [], function success (tx, results) {	        
		var len = results.rows.length;
		var amou;
		var type;
		var dateini;
		var datend;
		console.log("Metas Vencidas "+len);
		if (len > 0) {
            for (var i = 0; i < len; i++) { 	
            	type = results.rows.item(i).type_assigned;
            	amou = results.rows.item(i).amount;
            	dateini = results.rows.item(i).start_period;
            	datend = results.rows.item(i).finish_period;
            	id_server_sale_assigned = results.rows.item(i).id_server;
            	console.log("Tipo de meta "+type +" Monto Asignado "+amou+" fecha inicio "+dateini+" fecha fin "+datend);
            	switch(type){
            		case 1:
            			get_data_call(dateini, datend, id_server_sale_assigned);
            		break
            		
            		case 2:
            			get_data_sale(dateini, datend, id_server_sale_assigned);
            		break;
            		
            		case 3:
            			get_data_meeting(dateini, datend, id_server_sale_assigned);
            		break;
            		
            		case 4:
            			get_data_proposal(dateini, datend, id_server_sale_assigned);	
            		break;
            	}
            }          
        } else {
            console.log("No hay metas vencidas para enviar");
        } 	  		    		    
	}, errorCB);	
}


function get_data_meeting(date_ini, date_end, idserver){	        
	executeSql("SELECT COUNT(id) AS reuniones from schedule WHERE DATE(creation_date) BETWEEN ? AND ?", [date_ini, date_end], function sucessname (tx, results) {	
		var len = results.rows.length;		
		if (len > 0) {
            for (var i = 0; i < len; i++) {
            	var total_meeting = results.rows.item(i).reuniones;
            	console.log("Reuniones Realizadas Finalmente "+total_meeting);
            	send_report_final(idserver, total_meeting);
            }          
        } else {
            console.error("Error Sumando Reuniones para enviar");
        } 	  		    		    
	}, errorCB);
}

function get_data_proposal(date_ini, date_end, idserver){
	executeSql("SELECT SUM(reu_efec) AS propuestas from schedule WHERE reu_efec = ? AND creation_date BETWEEN ? AND ?", [1, date_ini, date_end], function success (tx, results) {
		var len = results.rows.length;		
		if (len > 0) {
            for (var i = 0; i < len; i++) {
            	var total_proposal = results.rows.item(i).propuestas;
            	console.log("Propuestas Realizadas Finalmente "+total_proposal);
            	send_report_final(idserver, total_proposal);
            }          
        } else {
            console.error("Error Sumando Propuestas para enviar");
        } 	  		    		    
	}, errorCB);
}


function get_data_sale(date_ini, date_end, idserver){	
	executeSql("SELECT SUM(value_sale) AS ventas from sales WHERE creation_date_sale BETWEEN ? AND ?", [date_ini, date_end], function success (tx, results) {
		var len = results.rows.length;		
		if (len > 0) {
            for (var i = 0; i < len; i++) {
            	var total_sale = results.rows.item(i).ventas;
            	console.log("Ventas Realizadas Finalmente "+total_sale);
            	send_report_final(idserver, total_sale);
            }          
        } else {
            console.error("Error Sumando Propuestas para enviar");
        } 	  		    		    
	}, errorCB);
}
 
 
function get_data_call(date_ini, date_end, idserver){
	executeSql("SELECT SUM(cntcall) AS llamadas from calldia WHERE date_noti BETWEEN ? AND ?", [date_ini, date_end], function sucessname (tx, results) {	        
		var len = results.rows.length;		
		if (len > 0) {
            for (var i = 0; i < len; i++) {
            	var total_calls = results.rows.item(i).llamadas;
            	console.log("Llamadas Realizadas Finalmente "+total_calls);
            	send_report_final(idserver, total_calls);
            }          
        } else {
            console.error("Error Sumando llamadas para enviar");
        } 	  		    		    
	}, errorCB);
}


function send_report_final(idserver, cant_to_send){
	$.ajax({
        type: "POST",
        url: ubication + "send_report_final.php",
        data: ({
        	idregister: idserver,
            enterprise: enterprise_ID,
            namesaller : nameu_co,
            count: cant_to_send,
			timeout: 25000,
        }),
        async: true, 
        success: function(datos) {        	
        	if(datos!=0){
        		console.log("Registro final de reporte actualizado correctamente en la central");
        	} else{
        		console.warn("Registro final de reporte ya se encuentra actualizado en la central");
        	}                   
        },
        error: function(obj, error, objError) {
            console.error("Error accediendo a la pagina send_report_final.php");
        }
    });
}


function get_date_last_call(){
	executeSql("SELECT date_noti FROM calldia ORDER BY date_noti  DESC LIMIT 1", [], function success (tx, results) {	        
		var len = results.rows.length;
		var reset_count_call = 0;
		if (len > 0) {
            for (var i = 0; i < len; i++) { 	 
            	data_last_day_call 	= results.rows.item(i).date_noti; 
            	if (Date.parse(datenow) > Date.parse(data_last_day_call)) {            		
                   $('#lbl_count_call').html(reset_count_call);
                }
            }          
        } else {
            console.error("No hay registros de llamadas");
        } 	  		    		    
	}, errorCB);					
}


function display_data_assigned(){
    executeSql("SELECT * FROM assigned", [], function Success(tx, results) {
        var len = results.rows.length; 
        if (len > 0) {
            for (var i = 0; i < len; i++) { 	 
                console.log("ID_SERVER =>"+results.rows.item(i).id_server+"   ID_SELLER =>"+results.rows.item(i).id_seller+"   AMOUNT =>"+results.rows.item(i).amount+ "   TYPE =>"+results.rows.item(i).type_assigned+  "   START_DATE =>"+results.rows.item(i).start_period+ "   END_DATE =>"+results.rows.item(i).finish_period+ "   TOTAL_REPORTED =>"+results.rows.item(i).total_reported+ "   DATE_REPORTED =>"+results.rows.item(i).date_reported);
            }          
        } else {
            console.error("No se encontraron metas asignadas");
        }
    }, errorCB);
}
   
function getname_seller(number_phone){ 
	$.ajax({
        type: "POST",
        url: ubication + "getname_seller.php",
        data: ({
            my_num_phone: numberPhone,
			timeout: 25000,
        }),
        async: true, 
        success: function(datos) {        	
        	var dataJson = eval(datos);
            for (var i in dataJson) {
            	var name_sell = dataJson[i].myname_current;            	
            	console.log("Obtenido nombre del vendedor correctamente desde la central como: "+datos);
            	update_myname_seller(name_sell);
            }                    
        },
        error: function(obj, error, objError) {
            console.error("Error accediendo a la pagina getname_seller.php");
        }
    });
}
 
function update_myname_seller(name_current_seller){
	   executeSql("UPDATE controlapp SET nameuserco = ? WHERE id = ?", [name_current_seller, 1], function sucessname (tx, results) {	        
	        	console.log("Nombre del vendedor actualizado correctamente");
	        	//trae el nombre del vendedor para mostrar mensaje de bienvenida
	        	queryUpdatenameco(); 		
	            $("#saludo").html("Bienvenido " + nameu_co);
	        
	        
	    }, errorCB);
} 
    
function get_data_call_day(){
    executeSql("SELECT * FROM calldia WHERE sincr = ?", [0], function Success(tx, results) {
        var len = results.rows.length;
        console.log("Registros de llamadas obtenido para enviar: " + len); 
        if (len > 0) { 
            for (var i = 0; i < len; i++) {
            	var id = results.rows.item(i).id;
            	var dateini = results.rows.item(i).dateini;
            	var count = results.rows.item(i).cntcall;
                console.log(" dateini: "+dateini+" cntcall: "+count+" sincr: "+results.rows.item(i).sincr);                
                send_data_call_server(id, dateini, count);
            }          
        } else {
            console.log("No se encontro registro de llamadas para subir al servidor");
        }

    }, errorCB);
    
}


 
function send_data_call_server(id_local_app, _date, quantity) {
    $.ajax({
        type: "POST",
        url: ubication + "send_datacall_server.php",
        data: ({
        	name_seller: nameu_co,
            date_register: _date,
            quantity: quantity, 
            enterp_id: enterprise_ID,    
        }), 
        async: true, 
        success: function(datos) { 
                	if(datos!=0){
                		console.log("Registro de llamada subido correctamente al servidor");
                		//se actualiza el registro a estado de la sincronizacion a 1
                		Call_Sinchr_Update(id_local_app, 1);
                	}
                	else {
                		console.error("Registro de llamada no se pudo subir al servidor");
                    }
                              
        },
        error: function(obj, error, objError) {
            console.error("Error accediendo a la pagina send_datacompany_server.php");
        }
    });

}

function Call_Sinchr_Update(id_app_sale, sincro_status) {
    executeSql('UPDATE calldia SET sincr = ? WHERE id = ?', [1, id_app_sale], function(tx, results) {
        console.log("Item de Llamada Sincronizado Correctamente");	           
    }, function(err) {
        console.error(" Error " + err);
    });
}

    executeSql("SELECT enterprise_id FROM controlapp WHERE id = ?", [1], function Success(tx, results) {
        var len = results.rows.length; 
        if (len > 0) {
            for (var i = 0; i < len; i++) {
                enterprise_ID = results.rows.item(i).enterprise_id;
                console.log("enterprise_ID Obtenido:  " + enterprise_ID);
            }          
        } else {
            console.error("enterprise_ID No found ");
        }

    }, errorCB);


	executeSql("SELECT version_company, version_contact  FROM controlapp WHERE id = ?", [1], function Success(tx, results) {
            var len = results.rows.length;
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    version_company_local = results.rows.item(i).version_company;
					version_cont_local = results.rows.item(i).version_contact;
                    console.log("Version actual de Compaï¿½ias Local " + version_company_local);
					console.log("Version actual de Contactos Local " + version_cont_local);
                } 
            } 
             
        }, errorCB);  

    setInterval(start_sinchronized, 30000);
    
    //revisa cada minuto si hay que sicronizar ventas, nombre de vendedor.
    setInterval(start_sinchronized_report, 60000);
    
    //revisa cada 50 segundos si hay que sicronizar ventas, nombre de vendedor.
    setInterval(start_sinchronized_other, 50000);
 
    function start_sinchronized() { 
         
		checkConnection();    
        //si hay internet 
        if (conn) {
            console.warn("Validando sincronizacion");
			//revisa si hay companias, contactos, y citas que sincronizar desde al app hacia el servidor
            	sinchonized_company();
			//revisa si hay contactos que sincronizar desde el servidor hacia la app
            							//getVersioncContact();
            	getVersioncContact_app();
			//revisa si hay compaï¿½ias que sincronizar desde el servidor hacia la app
            	getVersionCompany_app();
			//revisa si hay reuniones que sincronizar desde al app hacia el servidor
            			//Sinchr_schedule(); 
			//revisa si hay registros de llamadas que enviar
            	get_data_call_day();
        }else{
			console.warn("No hay internet");	
		}
    }
    
    function start_sinchronized_other() { 
		checkConnection(); 
        //si hay internet 
        if (conn) { 
			//revisa si hay ventas que sincronizar 
        		sinchonized_sales();
			//revisa si hay que sincronizar el nombre del vendedor
        		getname_seller(numberPhone);
        	//revisa si hay que sincronizar las ventas asignadas del vendedor	
				get_sales_assigned();
			//revisa si hay reuniones que eliminar en la central
				get_meetin_to_delete();		  
        }else{
			console.warn("No hay internet");
		}
    }
     
          
    function start_sinchronized_report() {   
		checkConnection();  
        //si hay internet 
        if (conn) {
        	get_report();
        }else{
			console.warn("No hay internet para enviar reportes finales");	
		}
    }
       
    		 
    function get_meetin_to_delete(){
    	executeSql("SELECT id_app FROM  auxdelete", [], function sucessname (tx, results) {	                
    		var len = results.rows.length; 
    		console.log("Registros de reuniones por eliminar "+len);
    		if (len > 0) {
    			for (var i = 0; i < len; i++) {
    				var id_app_meeting = results.rows.item(i).id_app;	
    				sincronize_delete_meeting(id_app_meeting);
    			}
    		}
    		else{
    			console.log("No hay reuniones por eliminar");
    		}
    }, errorCB);
    } 
    

	function sinchonized_sales() {
	console.log("Buscando ventas por sincronizar ");
        executeSql('SELECT * FROM sales WHERE sincr = ?', [0], function(tx, results) {
            var len = results.rows.length; 
            //si hay algun registro que subir al servidor
            if (len > 0) { 
                console.log("Cantidad de ventas por sincronizar => " + len);
                for (var i = 0; i < len; i++) {
                	var id = results.rows.item(i).id;
                    var id_contact = results.rows.item(i).id_contact;
                    var value_sale = results.rows.item(i).value_sale;
                    var date_sale = results.rows.item(i).date_sale;
                    var observ = results.rows.item(i).obs;
                    var company_id = results.rows.item(i).company_id;
                    var enterprise_id = results.rows.item(i).enterprise_id;
                    getnameCompany(id, id_contact, value_sale, date_sale, observ, company_id, enterprise_id, nameu_co); 
                }      
            } 
            else {
                console.log("No Hay ventas que sincronizar");
            }
        }, function(err) {
            console.error(" Error " + err);
        });
    }
	
	
	function getnameCompany(id, id_contact, value_sale, date_sale, observ, company_id, enterprise_id, nameu_co){
		var name_comp="";
		console.log("Consultando nombre de compania con id => "+company_id);
		executeSql("SELECT name FROM company WHERE id = ?", [company_id], function Success(tx, results) {
            var len = results.rows.length;
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    name_comp = results.rows.item(i).name;
                    console.log("Nombre compania obtenido => "+name_comp);
                    send_datasales_server(id, id_contact, value_sale, date_sale, observ, name_comp, enterprise_id, nameu_co);
                } 				
            }else{
            	//si el id de la compania es cero, es decir fue venta a una persona natural
            	console.log("Nombre compania seteado a => Personal");
            	name_comp = "Personal";
            	send_datasales_server(id, id_contact, value_sale, date_sale, observ, name_comp, enterprise_id, nameu_co);
            }
            
        }, errorCB);
	}
	
	    function send_datasales_server(id, id_contact, value_sale, date_sale, observ, name_comp, enterprise_id, nameu_co) {  
        $.ajax({
            type: "POST",
            url: ubication + "send_datasales_server.php",
            data: ({
                id_con: id_contact,
                value: value_sale,
                date_sale: date_sale,
                obs: observ, 
                name_company: name_comp,
                enterp_id: enterprise_id,
                name_seller: nameu_co,
				timeout: 25000,
            }),
            async: true, 
            success: function(datos) {
                      
                    	if(datos!=null){
                    		console.log("Registro de venta subida correctamente al servidor");
                    		//se actualiza el registro a estado de la sincronizacion a 1
                    		Sale_Sinchr_Update(id, datos, 1);
                    	}
                    	else {
                    		console.error("Registro de venta no se pudo subir al servidor");
                        }
                                  
            },
            error: function(obj, error, objError) {
                console.error("Error accediendo a la pagina send_datacompany_server.php");
            }
        });

    }
	    
	
	    function Sale_Sinchr_Update(id_app_sale, id_server_company, sincro_status) {
	        executeSql('UPDATE sales SET company_id = ?, sincr = ? WHERE id = ?', [id_server_company, 1, id_app_sale], function(tx, results) {
	            console.log("Venta Sincronizada Correctamente");	           
	        }, function(err) {
	            console.error(" Error " + err);
	        });
	    } 
	    

	function getVersionCompany_app() {
	 console.warn("****** Consultando cambios en el servidor para companias ********");
        executeSql("SELECT version_company FROM controlapp WHERE id = ?", [1], function Success(tx, results) {
            var len = results.rows.length;
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    version_company_local = results.rows.item(i).version_company;
                    console.log("Version actual de Companias Local " + version_company_local);
                } 
				getcompany_server();
            } 
        }, errorCB);       
    } 

	 
    function getcompany_server() {
        $.ajax({
            type: "POST",
            url: ubication + "getcompany_server.php",
            data: ({
                enterprise: enterprise_ID,
				version_compan: version_company_local,
				name_seller: nameu_co,
				timeout: 25000,
            }), 
            async: true,
            success: function(datos) {
                var dataJson = eval(datos);
                
                for (var i in dataJson) {

                    var id = dataJson[i].myserver_id_company;
                    console.log("Procesar nueva empresa con id_server => " +id);

                    var id_server = dataJson[i].myserver_id_company;
                    var name_company = dataJson[i].myserver_name_company;
                    var address_company = dataJson[i].myserver_address_company;
                    var creation_date_company = dataJson[i].myserver_creation_date;
                    var create_user_name_company = dataJson[i].myserver_create_user_name;
                    var enterprise_id_company = dataJson[i].myserver_enterprise_id;
					var version_company_server = dataJson[i].myserver_version_company;

                    insert_or_update_companies(id_server, name_company, address_company, creation_date_company, create_user_name_company, enterprise_id_company, 1);
					updateversion_company_app(version_company_server);
                }
            }, error: function(obj, error, objError) { 
            }
        });
    }

	function updateversion_company_app(number_version) {
        executeSql("UPDATE controlapp SET version_company = ? WHERE id = ?", [number_version, 1], function Success(tx, results) {
            console.log("Nueva Version De Compania Actualizada");
        }, function errorupdateversion() {
            console.error("Error Update Version Contact");
        });
    }

    function insert_or_update_companies(id_server, name_company, address_company, creation_date_company, create_user_name_company, enterprise_id_company, status) {
        //executeSql("SELECT * FROM company WHERE id_server = ?", [id_server], function Success(tx, results) {
        	executeSql("SELECT * FROM company WHERE name = ?", [name_company], function Success(tx, results) {

            var len = results.rows.length;

            if (len > 0) {
                console.log("Actualizando " + name_company + " Correctamente en id_server => "+id_server);
                    update_company_app(id_server, address_company, 1, name_company);
                   
            } else {
                console.log("Insertando " + name_company);
                make_company(id_server, name_company, address_company, creation_date_company, create_user_name_company, enterprise_id_company, 1);
            }
        }, function error(err) {
            console.error("Error descargado registro de compaï¿½ias desde el server " + err);
        });
    }
  

    function update_company_app(id_server, address_company, status, name_company) {
        //executeSql("UPDATE company SET address = ?, sincr = ?, name = ? WHERE id_server = ?", [address_company, status, name_company, id_server], function Success(tx, results) {
        executeSql("UPDATE company SET address = ?, sincr = ?,  id_server = ? WHERE name = ?", [address_company, status, id_server, name_company], function Success(tx, results) {
            console.log(name_company + " Se ha Actualizado Correctamente");
            ChangeNameCompany_contact(id_server, name_company);
        }, function error(err) {
            console.error("Error Actualizado " + name_company);
        });
    }
    
    
    function ChangeNameCompany_contact(id_server, name_company){
    	executeSql("SELECT * FROM contact WHERE company_id = ?", [id_server], function Success(tx, results) {    		
    		var len = results.rows.length;
    		console.log("Contactos por modificar el nombre de empresa => " + len);	
    		if (len > 0) { 
    			for (var i = 0; i < len; i++) {
    				 var name_contact =  results.rows.item(i).name; 
                     update_company_to_contact(id_server, name_company, name_contact);
                }    
            }
    		
    	}, function error(err) {
            console.error("Error consultando contactos para modificar compania => " + name_company);
        });
    }
    
    
    function update_company_to_contact(id_company, name_company, name_contact){
    	executeSql("UPDATE contact SET name_company = ? WHERE company_id = ?", [name_company, id_company], function Success(tx, results) {    		
    		console.log("Compania actualizada para el contacto =>" + name_contact);
    	}, function error(err) {
            console.error("Error Actualizado " + name_company +" para el contacto => "+name_contact);
        });
    }


    function make_company(id_server, name_company, address_company, creation_date_company, create_user_name_company, enterprise_id_company, status) {
        executeSql("INSERT INTO company (id_server, name, address, creation_date, create_user_name, enterprise_id, sincr) VALUES(?,?,?,?,?,?,?);",
                [id_server, name_company, address_company, creation_date_company, create_user_name_company, enterprise_id_company, status], function Success(tx, results) {
            console.log(name_company + " Insertada Correctamente");

        }, function error(err) {
            console.error("Error descargado registro de compaï¿½ias desde el server " + err);
        });
    }
 

 
    //obtiene cantidad de llamadas para mostrar en la pagina principal
    db.transaction(QueryCallCount, errorCB);

    executeSql("SELECT * from schedule", [], success_efective, errorCB);

    function success_efective(tx, results) {
        var len = results.rows.length;
        console.log("Reuniones : " + len);
        for (var i = 0; i < len; i++) {
            console.log("ID_APP = " + results.rows.item(i).id + " ID contacto= " + results.rows.item(i).id_contact + " Fecha de registro = " + results.rows.item(i).creation_date+ " Fecha de reuni\u00f3n =  " + results.rows.item(i).date_reu_ini + " Fecha fin de la reuni\u00f3n =  " + results.rows.item(i).date_reu_fin  + " Fue Propuesta =  " + results.rows.item(i).reu_efec + " Observaciones =  " + results.rows.item(i).obs + " company_id =  " + results.rows.item(i).company_id + " enterprise_id =  " + results.rows.item(i).enterprise_id + " sincr =  " + results.rows.item(i).sincr + " Direccion =  " + results.rows.item(i).address + " Re-agendada =  " + results.rows.item(i).meeting_re);
        }
    }


    executeSql("SELECT * from sales", [], count_sales, errorCB);

    function count_sales(tx, results) {
        var len = results.rows.length;
        console.log("Sales : " + len);
        for (var i = 0; i < len; i++) {
            console.log( "ID contacto= " + results.rows.item(i).id_contact + " Valor =  " + results.rows.item(i).value_sale + " Fecha de Venta =  "+ results.rows.item(i).date_sale + " Fecha de Creacion =  "+ results.rows.item(i).creation_date_sale + " Obs =  "+ results.rows.item(i).obs + " company_id =  "+ results.rows.item(i).company_id+ " enterprise_id =  "+ results.rows.item(i).enterprise_id+ " sincr =  "+ results.rows.item(i).sincr);
        }
    }

    executeSql('SELECT * FROM contact', [], function(tx, results) {
        var len = results.rows.length;
        console.log("Listado de los (" + len + ") contactos de siguelos");
        for (var i = 0; i < len; i++) {
            console.log("id => " + results.rows.item(i).id + " id_server => " + results.rows.item(i).id_server + " Nombre Compaï¿½ia => " + results.rows.item(i).name_company + " company_id => " + results.rows.item(i).company_id + " name => " + results.rows.item(i).name +" role => " + results.rows.item(i).role + " phone1 => " + results.rows.item(i).phone1 + " phone2 => " + results.rows.item(i).phone2 + " address => " + results.rows.item(i).address +" creation_date => " + results.rows.item(i).creation_date + " creation_user_name => " + results.rows.item(i).creation_user_name + " enterprise_id => " + results.rows.item(i).enterprise_id +" sincr => " + results.rows.item(i).sincr);
        }
    }, function(err) {

    });


    executeSql('SELECT * FROM company', [], function(tx, results) {
        var len = results.rows.length;
        console.log("Listado de las (" + len + ") compaï¿½ias de siguelos");
        for (var i = 0; i < len; i++) {
            console.log("id => " + results.rows.item(i).id + " id_server => " + results.rows.item(i).id_server + " Nombre Compaï¿½ia => " + results.rows.item(i).name + " address => " + results.rows.item(i).address + " creation_date => " + results.rows.item(i).creation_date + " create_user_name => " + results.rows.item(i).create_user_name + " enterprise_id => " + results.rows.item(i).enterprise_id +" sincr => " + results.rows.item(i).sincr);
        }
    }, function(err) {

    });

    executeSql('SELECT nameuserco FROM controlapp WHERE id = ?', [1], queryNameUserSuccess, errorCB);

    function queryNameUserSuccess(tx, results) {
        var len = results.rows.length;
        for (var i = 0; i < len; i++) {
            console.log("Nombre de Comercial =>"+ results.rows.item(i).nameuserco);
            nameu_co = results.rows.item(i).nameuserco;
        }
    }


    function CreateTableSuccess() {
        console.log("Table created Success");
    }

    function CreateTableError(err) {
        console.error("Error create table " + err.code);
    }

    //control of application for login
    db.transaction(queryDBControlapp, errorCB);

    function queryDBControlapp(tx) {
        tx.executeSql('SELECT * FROM controlapp', [], function Success(tx, results) {
            var len = results.rows.length;           												
            if (len == 0) {
                console.log("table controlapp is empty.. inserting register whit values zero all");
                tx.executeSql('INSERT INTO controlapp (code_activ, status_activ, sms_processing, phone, role, nameuserco, version_company, version_contact, enterprise_id, version_app) values (?,?,?,?,?,?,?,?,?,?);', [0, 0, 0, 0, 3, null, 0, 0, 0, 0], insertSuccessControlapp, insertFailed);
            }

            tx.executeSql('SELECT * FROM controlapp', [], Success_qdbControlapp, errorCB);

            for (var i = 0; i < len; i++) {
                console.log("ID = " + results.rows.item(i).id + " code_activ = " + results.rows.item(i).code_activ + " status_activ =  " + results.rows.item(i).status_activ + " sms_processing =  " + results.rows.item(i).sms_processing + " Phone =  " + results.rows.item(i).phone + " Role =  " + results.rows.item(i).role + " Nombre del Comercial =  " + results.rows.item(i).nameuserco + " Version de Compaï¿½ias =  " + results.rows.item(i).version_company + " Version de Contactos =  " + results.rows.item(i).version_contact + " Enterprise ID =  " + results.rows.item(i).enterprise_id);
                numberPhone = results.rows.item(i).phone; 
                version_app = results.rows.item(i).version_app;
                console.log("Numero Telefonico actual es: "+numberPhone+" Version APP: "+version_app);    
            }            
        }, errorCB);
    }  

    function errorCB(err) {
        console.log("Error SQL " + err.code);
    }

  
    //response error to insert for values default in tables Controlapp
    function insertFailed(err) {
        console.error("Error inserting in Controlapp" + err.code);
    }


    function insertSuccessControlapp(tx, results) {
        console.log("Nuevo registro insertado en Controlapp");
    }

    //checked status register application
    function Success_qdbControlapp(tx, results) {
        var len = results.rows.length;
        var status_activity;
        var sms_activity;
        var myrole;
        var myname;

        //variable for validate el field status_activation => activation OK, 0=> not have activation
        for (var i = 0; i < len; i++) {
            status_activity = results.rows.item(i).status_activ;
            sms_activity = results.rows.item(i).sms_processing;
            myrole = results.rows.item(i).role;
            numberPhone = results.rows.item(i).phone;
            myname = results.rows.item(i).nameuserco;           
        }

        if (status_activity == 1 && sms_activity == 1 && myrole == 0) {
            $("#login").css("display", "none");
            $.mobile.changePage("#index_sa");
        } else if (status_activity == 1 && sms_activity == 1 && myrole == 1) {
            $("#login").css("display", "none");
            $.mobile.changePage("#index_ma");
        } else if (status_activity == 1 && sms_activity == 1 && myrole == 2) {
            $("#login").css("display", "none");
            $.mobile.changePage("#index_co");
        } else {
            $("#login").css("display", "block");
            if (sms_activity == 0) {
                $("#screen_activation").css("display", "none");
                $("#screen_register").css("display", "block");
            } else {
                $("#screen_register").css("display", "none");
                $("#screen_activation").css("display", "block");
            }
        }
    } 
    
    
 	
   $(document).on('click', '#btn_register', function() {
    	var register;        
    	numberPhone = $("#my_number_phone").val();
        if(numberPhone != ""){ 
 
        	 $.ajax({  
                 type: "POST",
                 url: ubication + "register_app.php",
                 data: ({
                     nphone: numberPhone,
     				 timeout: 25000,
                 }), 
                 async: true,
                 success: function(datos) {
                     if(datos > 0){
                    	 version_app = datos;
                    	 db.transaction(queryUpdateControlapp, errorCB);
                         db.transaction(queryDBControlapp, errorCB);
                         send_sms_code();
                     }else if(datos < 0){
                    	 
                         Dialog(" Comprube que el numero ingresado no este registrado, y/o valide que el numero este correcto", function(){}, "error");
                     }   
                 },  
                 error: function(obj, error, objError) {
                	 console.error("Error "+error);
                 }
             }); 
        }else{
        	Dialog("Ingrese un numero v\u00e1lido?", function(){}, "info");
        }
	});
      
    
    function send_sms_code(){
    	$.ajax({  
    	                 type: "POST",
    	                 url: ubication + "sms_sendCode.php",
    	                 data: ({
    	                     nphone: numberPhone,
    	     				 timeout: 25000,
    	                 }),
    	                 async: true,
    	                 success: function(datos) { 	                	 
    	                	 if(datos != null){
    	                		 console.log("SMS Procesado Correctamente");
    	                	 }else{
    	                		 console.error("SMS no se pudo procesar");
    	                	 }
    	                 },
    	                 error: function(obj, error, objError) {
    	                	 console.error("Error "+error);
    	                 }
    	             });
    }


    function queryUpdateControlapp(tx) {
        tx.executeSql('UPDATE controlapp SET sms_processing = ?, phone = ?, version_app = ?  WHERE id = 1', [1, numberPhone, version_app], queryUpdateSms_processing, errorCB);
    }


    function queryUpdateSms_processing() {
        console.log("sms_processing, phone y version_app actualizados correctamente");
    }


    $(document).on('click', '#btn_activation', function() {
        var codein = $("#my_number_code").val();
        $.ajax({
            type: "POST",
            url: ubication + "getrole.php",
            data: ({
                nphone: numberPhone,
				timeout: 25000,
            }),
            async: true,
            success: function(datos) {
                var dataJson = eval(datos);

                for (var i in dataJson) {
                    roleUser = dataJson[i].role;
                    nameu_co = dataJson[i].name;
                    enterprise_ID = dataJson[i].enterpriseID;
                }
				
                queryUpdateControlappNameco();
            },
            error: function(obj, error, objError) {
            	console.error("Error "+error);
            }
        });

        $.ajax({
            type: "POST",
            url: ubication + "activation.php",
            data: ({
                nphone: numberPhone,
                code: codein,
				timeout: 25000,
            }),
            cache: false,
            dataType: "text",
            success: onSuccessActivity
        });
        function onSuccessActivity(data) {
            var register = data;

            if (register == 1) {
                db.transaction(queryUpdateActivation, errorCB);
                db.transaction(queryDBControlapp, errorCB);
            } else {
            	Dialog(" No se pudo validar!", function(){}, "error");
            }
        } 
    });

    function queryUpdateActivation(tx) {
        tx.executeSql('UPDATE controlapp SET status_activ = ?, role = ?, enterprise_id = ? WHERE id = ?', [1, roleUser, enterprise_ID, 1], queryUpdateActivationSuccess, errorUpdateActivation);
    }

    function queryUpdateActivationSuccess(tx, results) {
        console.log("Query Update Activation Success");
    }

    function errorUpdateActivation() {
        console.error("Error query Update Activation Failed ");
    }


    $('#search_today').click(function() {
    	//variable para contrlar que mostrar al ingresar a la pagina de citas
    	control_display_quot = 1;
		
		quotes = document.getElementById('calendar');
		$(quotes).children().remove('div .cita');
		
		var daycurrent = ""+day;
		var monthcurrent = ""+month;
		
		if(daycurrent.length==1){
			daycurrent = "0"+day;
		}
		
		if(monthcurrent.length==1){
			monthcurrent = "0"+month;
		}
				
		var fech_current_new = year + "-" + monthcurrent + "-" + daycurrent;
		quotedaycurrent1 = fech_current_new + " 00:00:00";
		quotedaycurrent2 = fech_current_new + " 23:59:00";
		search_display_today();
    	
		

		$(quotes).on("click", ".cita", function(e) {
			ID_CON = this.id;
			id_quote_schedule = this.getAttribute("name");
			quotes = document.getElementById('calendar');
            $(quotes).children().remove('div .cita');
			get_address_meeting(id_quote_schedule);    
		});
	});
    
    
    function search_display_today(){
    	executeSql("SELECT * FROM schedule WHERE sincr = ?", [0], function sucessname (tx, results) {
            var len = results.rows.length;
            console.log("Reuniones sin soncronizar "+len);
            if (len > 0) {     
            	db.transaction(getQuotDaySI, errorCB);    
            }            
            db.transaction(getQuotDay, errorCB);        
        }, errorCB);
    }

    //event for controller per meddle of the variable ctrl_new_to_presave if user is new
    $('#coll_nu').click(function() {
        ctrl_new_to_presave = 1;
    });
    
    //event for controller per meddle of the variable ctrl_new_to_presave if user was before save
    $('#coll_pre').click(function() {
        ctrl_new_to_presave = 2;
    });


 
    // event for go from index a schedule
    $('#btn_specify').click(function() {
        if (ctrl_new_to_presave != 0) {
            if (ctrl_new_to_presave == 1) { //if is new
                convalue = $("#name_user").val();
                if (convalue.length > 5) {
                    //reset field name user empty
                    $('#name_user').val("");
                    $.mobile.changePage("#specify");
                } else {
                    Dialog("Debe ingresar un contacto v\u00e1lido, mayor a 5 caracteres?", function(){}, "warning");
                }

            } else if (ctrl_new_to_presave == 2) { //if is user exist
                convalue = $("#prof_list_contacts option:selected").text();
                if (convalue != "Seleccione Contacto") {
                    //reset field name user empty
                    $('#name_user').val("");
                    $.mobile.changePage("#specify");
                } else {
                    Dialog("Debe seleccionar o ingresar un contacto v\u00e1lido?", function(){}, "warning");
                }
            } 
        } else { 
        	Dialog("Debe seleccionar o ingresar un contacto v\u00e1lido?", function(){}, "warning");
              
        }
    });

    function queryUpdateControlappNameco() {
        executeSql('UPDATE controlapp SET nameuserco = ? WHERE id = ?', [nameu_co, 1], queryUpdatenameco, errorCB);
    }

    function queryUpdatenameco() {
        console.log("Nombre de comercial Actualizado");
        db.transaction(querynew_nameCo, errorCB);
    }

    function querynew_nameCo(tx, results) {
        tx.executeSql('SELECT * FROM controlapp', [], querySuccessnameCo, errorCB);
    }

    function querySuccessnameCo(tx, results) {
        var len = results.rows.length;
        //query the last contact insert in the table Contact for get your ID
        if (len > 0) {
            for (var i = 0; i < len; i++) {
            	nameu_co = results.rows.item(i).nameuserco;
                console.log("Nombre de Comercial Actualizado a: "+ nameu_co);    
            }
        } else {
        	console.log("No se encontraron datos en controlapp");
        }

    }

    
    
    //event for add an new company to list (add_company)
    $("#btn_add_new_company").on("click", function() {
        var name = $("#new_company").val();
		var address = $("#address_company").val();
		 
		if(name.length > 0 && address.length > 0) {		
	        search_company_exist(name, address);	        
		}else{
			 Dialog("Ingrese un nombre y una direcci\u00f3n para la empresa?", function(){}, "warning");
		}  			
    });

    function search_company_exist(name, address) {
        var id = '1';
        executeSql("SELECT * from company WHERE name = ?", [name], function(tx, results) {
            console.log("Buscando Compania..");
            var len = results.rows.length;
            if (len == 0) {
            	confirmDialog(" Desea agregar la nueva empresa <br>Nombre: "+name+"<br>Direccion: "+address, function(){
            		add_company(name, address);
                    $('#list_companies').append('<option value=' + id + '>' + name + '</option>');
                    //display selected the new item make
                    $('#list_companies option').filter(function() {
                        return $(this).html() == name;
                    }).prop('selected', true);
                    $('#list_companies').selectmenu().selectmenu('refresh', true);
            	});
                 
            } else {
                console.warn("La Compania no se puede agregar por que ya existe..");
                Dialog("La Compania ya existe?", function(){}, "warning");
                $('#name_user').val("");
            }
        }, function(err) {
 
        }); 
    }   
 
    function add_company(name_company, address_company) {	
        executeSql("INSERT INTO company (id_server, name, address, creation_date, create_user_name, enterprise_id, sincr)" +
                " VALUES (?,?,?,?,?,?,?)", [0, name_company, address_company, datenow, nameu_co, enterprise_ID, 0], function(tx, results) {
            console.log("Insert Company processing...");
            $("#div_new_company").css("display", "none");
        }, function(err) {
        	console.error("Error Insertando en tabla company");
        });  
    }
 
    // event for set and display variables in page (schedule)
    $(document).on('pagebeforeshow', '#specify', function() {
    	$("#div_conf_reu").css("display", "block");
    	$('#date_quote').val("");
        $('#hour_quote').val("");
        $('#hour_fin_quote').val("");
        load_list_company();

        if (ctrl_new_to_presave == 2) {
            //call method that search the user passed for parameter
            setDisplayDataUser(convalue);
        } else if (ctrl_new_to_presave == 1) {
            //set values empty to fields page specify, but the user is new
            $('#tel_fix').val("");
            $('#tel_cel').val("");
            $('#posit_contact').val("");
            $('#address_contact').val("");
        }
        $('#name_contact').html('Contacto: ' + convalue);
    });
 
  
 
    function updateversion_contact(new_version) {

        executeSql("UPDATE controlapp SET version_contact = ? WHERE id = ?", [new_version, 1], function Success(tx, results) {
            console.log("Nueva Version De Contactos Actualizada");

        }, function errorupdateversion() {
            console.error("Error Update Version Contact");
        });
    }

    function updateversion_company(new_version) {

        executeSql("UPDATE controlapp SET version_company = ? WHERE id = ?", [new_version, 1], function Success(tx, results) {
            console.log("Nueva Version De Compaï¿½ia Actualizada");

        }, function errorupdateversion() {
            console.error("Error Update Version Contact");
        });
    }

    function sinchonized_company() {
console.log("Buscando companias por sincronizar ");
        executeSql('SELECT * FROM company WHERE sincr = ?', [0], function(tx, results) {
            var len = results.rows.length;
            //si hay algun registro que subir al servidor
            if (len > 0) {
                console.log("Cantidad de companias por sincronizar => " + len);
                for (var i = 0; i < len; i++) {
                    var id = results.rows.item(i).id;
                    var n_emp = results.rows.item(i).name;
                    var a_emp = results.rows.item(i).address;
                    var cre_date = results.rows.item(i).creation_date;
                    var cre_user = results.rows.item(i).create_user_name;
                    var id_enter = results.rows.item(i).enterprise_id;
                    //debe ir id compania local
                    send_datacompany_server(id, n_emp, a_emp, cre_date, cre_user, id_enter);
                } 
                
            }
            else {
                console.log("No Hay companias que sincronizar");
				sinchonized_contact();
            }
        }, function(err) {
            console.error(" Error " + err);
        });
    }
	
//************** inicio de metodos para descargar contactos y actualizar version contactos *******************//
	function getVersioncContact_app() {
        executeSql("SELECT version_contact FROM controlapp WHERE id = ?", [1], function Success(tx, results) {
            var len = results.rows.length;
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    version_contact_local = results.rows.item(i).version_contact;
                    console.log("Version Actual Local Contactos " + version_contact_local);
                }  
            }
            search_update_contact_server();
        }, errorCB);
    } 
	
	function search_update_contact_server() {
	console.warn("Consultando Actualizacion de contactos en el servidor...");
	console.warn("enviando version de contacto..."+version_contact_local);
        var value_sincron = 1;
        $.ajax({
            type: "POST",
            url: ubication + "controlversion_contact.php",
            data: ({
                version_cont_app: version_contact_local,
                enterprise: enterprise_ID,
                name_seller: nameu_co,
                timeout: 25000,  
            }),
            async: true,
            success: function(datos) {
                var dataJson = eval(datos);
                for (var i in dataJson) {
																		
                    var id_contact = dataJson[i].my_id_contact; 																		
                    var id = dataJson[i].my_id_contact;
                    var id_company = dataJson[i].my_id_company;
                    var name_contact = dataJson[i].my_name;
                    var role_contact = dataJson[i].my_role; 
                    var phone1_contact = dataJson[i].my_phone1;
                    var phone2_contact = dataJson[i].my_phone2;
                    var address_contact = dataJson[i].my_address;
                    var creation_date = dataJson[i].my_creation_date;
                    var create_user_name = dataJson[i].my_create_user_name;
                    var enterprise_id = dataJson[i].my_enterprise_id;
                    var name_compa = dataJson[i].my_name_company;
                    var version_contact_server = dataJson[i].my_version_server;

                    insert_or_update_contact_app(id_contact, id_company, name_compa, name_contact, role_contact, phone1_contact, phone2_contact, address_contact, creation_date, create_user_name, enterprise_id, value_sincron);                        
                    update_version_contact_app(version_contact_server);
                    
                    //continua consultando contactos persona natural 
                    get_sever_contact_naturals();
                }
            }, error: function(obj, error, objError) {
            }
        });  

    }
	
	
	function get_sever_contact_naturals() {
	console.warn("Consultando contactos naturales en el servidor...");
        $.ajax({
            type: "POST",
            url: ubication + "get_contact_natutal.php",
            data: ({
                enterprise: enterprise_ID,
                name_seller: nameu_co,
                timeout: 25000,  
            }),
            async: true,
            success: function(datos) {
                var dataJson = eval(datos);
                for (var i in dataJson) {
																		
                    var id_contact = dataJson[i].my_id_contact;																		
                    var id = dataJson[i].my_id_contact;
                    var id_company = dataJson[i].my_id_company;
                    var name_contact = dataJson[i].my_name;
                    var role_contact = dataJson[i].my_role;
                    var phone1_contact = dataJson[i].my_phone1;
                    var phone2_contact = dataJson[i].my_phone2;
                    var address_contact = dataJson[i].my_address;
                    var creation_date = dataJson[i].my_creation_date;
                    var create_user_name = dataJson[i].my_create_user_name;
                    var enterprise_id = dataJson[i].my_enterprise_id;
                    var name_compa = dataJson[i].my_name_company;
                    var version_contact_server = dataJson[i].my_version_server;

                    insert_or_update_contact_app(id_contact, id_company, name_compa, name_contact, role_contact, phone1_contact, phone2_contact, address_contact, creation_date, create_user_name, enterprise_id, value_sincron);                                            
                }
            }, error: function(obj, error, objError) {
            }
        });  

    }
	

	function insert_or_update_contact_app(id_contact, id_company, name_company, name_contact, role_contact, phone1_contact, phone2_contact, address_contact, creation_date, create_user_name, enterprise_id, sincronized) {
		executeSql('SELECT * FROM contact WHERE id_server = ?', [id_contact], function(tx, results) {//success function
            var len = results.rows.length;
            if (len == 0) {
			console.log("Insertando Contanto");
                executeSql("INSERT INTO contact (id_server, company_id, name_company, name, role, phone1, phone2, address, creation_date, creation_user_name, enterprise_id, sincr) " + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?);",
                        [id_contact, id_company, name_company, name_contact, role_contact, phone1_contact, phone2_contact, address_contact, creation_date, create_user_name, enterprise_id, sincronized], function Success(tx, results) {
                    
                    console.log("Registro descargado correctamente desde el servidor ");
					
                }, function error(err) {
                    console.error("Error descargado registro desde el server " + err);
                });
            } else {    
			console.log("Actualizando Contanto");			
               executeSql("UPDATE contact SET company_id = ?, name_company = ?, name = ?, role = ?, phone1 = ?, phone2 = ?, address = ?, creation_date = ?, creation_user_name = ?," + "enterprise_id = ?, sincr = ?  WHERE id_server = ?",
                        [id_company, name_company, name_contact, role_contact, phone1_contact, phone2_contact, address_contact, creation_date, create_user_name, enterprise_id, sincronized, id_contact], function Success(tx, results) {
                    console.log("Registro Sincronizado correctamente con el servidor ");
                }, function error(err) {
                    console.error("Error Sincronizado registro desde el server " + err);
                });
            }
        }, errorfunction);
    }

	function update_version_contact_app(new_version) {

        executeSql("UPDATE controlapp SET version_contact = ? WHERE id = ?", [new_version, 1], function Success(tx, results) {
            console.log("Nueva Version De Contactos Actualizada");

        }, function errorupdateversion() {
            console.error("Error Update Version Contact");
        });
    }
//************** fin metodos descargar contactos y actualizar version contactos *******************//

//************** inicio de metodos para descargar compaï¿½ias y actualizar version compaï¿½ias *******************//
function getVersioncCompany_app() {
        executeSql("SELECT version_company FROM controlapp WHERE id = ?", [1], function Success(tx, results) {
            var len = results.rows.length;
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    version_company_local = results.rows.item(i).version_company;
                    console.log("Version Actual Local Compaï¿½ias " + version_company_local);
                } 
            }
            search_update_company_server();
        }, errorCB);
    }

function search_update_company_server() {
	console.warn("Consultando Actualizacion de compaï¿½ias en el servidor...");
	console.warn("enviando version de compaï¿½ia..."+version_company_local+" enterprise_ID=> "+enterprise_ID);
        var value_sincron = 1;
        $.ajax({
            type: "POST",
            url: ubication + "controlversion_company.php",
            data: ({
                version_cont_app: version_company_local,
                enterprise: enterprise_ID,
                timeout: 25000, 
            }),
            async: true,
            success: function(datos) {
                var dataJson = eval(datos);
                for (var i in dataJson) {
																	
                    var id_company = dataJson[i].my_id_company;																		
                    var name_company = dataJson[i].my_name_company;                  
                    var address_company = dataJson[i].my_address_company;																
                    var date_creation = dataJson[i].my_creation_date;
                    var create_user = dataJson[i].my_create_user_name;
                    var enterprise_id = dataJson[i].my_enterprise_id;            
                    var version_company_server = dataJson[i].my_version_server_com;

 insert_or_update_company_app(id_company, name_company, address_company, date_creation, create_user, enterprise_id, value_sincron);
 update_version_company_app(version_company_server);
                }
            }, error: function(obj, error, objError) {
            }
        });  
    }

function insert_or_update_company_app(id_company, name_company, address_company, date_creation, create_user, enterprise_id, value_sincron) {
		executeSql('SELECT * FROM company WHERE id_server = ?', [id_company], function(tx, results) {//success function

            var len = results.rows.length;
            if (len == 0) {
			console.log("Insertando compaï¿½ia");
                executeSql("INSERT INTO company (id_server, name, address, creation_date, create_user_name, enterprise_id, sincr) " + " VALUES(?,?,?,?,?,?,?);",
                        [id_company, name_company, address_company, date_creation, create_user, enterprise_id, 1], function Success(tx, results) {
                    
                    console.log("Registro descargado correctamente desde el servidor ");
                }, function error(err) {
                    console.error("Error descargado registro desde el server " + err);
                });
            } else {    
			console.log("Actualizando compaï¿½ia");			
               executeSql("UPDATE company SET name = ?, address = ?, creation_date = ?, create_user_name = ?, enterprise_id = ?, sincr = ?  WHERE id_server = ?",
                        [name_company, address_company, date_creation, create_user, enterprise_id, 1, id_company], function Success(tx, results) {
                    console.log("Registro Sincronizado correctamente con el servidor ");
                }, function error(err) {
                    console.error("Error Sincronizando registro desde el server " + err);
                });	
            }
        }, errorfunction);
    }

function update_version_company_app(new_version) {
        executeSql("UPDATE controlapp SET version_company = ? WHERE id = ?", [new_version, 1], function Success(tx, results) {
            console.log("Nueva Version De Compania Actualizada");

        }, function errorupdateversion() {
            console.error("Error actualizando version de companias");
        });
    }

//************** fin metodos descargar compaï¿½ias y actualizar version compaï¿½ias *******************//
			
    function sinchonized_contact() { 
	console.warn("Buscando contactos por sincronizar");
        executeSql('SELECT * FROM contact WHERE sincr = ?', [0], function(tx, results) {
            var len = results.rows.length;
            if (len > 0) {
                console.log("Contactos por sincronizar => " + len);
                for (var i = 0; i < len; i++) {
                    var id = results.rows.item(i).id;
                    var name = results.rows.item(i).name;
                    var name_company = results.rows.item(i).name_company;
                    var role = results.rows.item(i).role;
                    var phone1 = results.rows.item(i).phone1;
                    var phone2 = results.rows.item(i).phone2;
                    var address = results.rows.item(i).address;
                    var creation_date = results.rows.item(i).creation_date;
                    var creation_user_name = results.rows.item(i).creation_user_name;
                    var enterprise_id = results.rows.item(i).enterprise_id;
                    
                    send_datacontact_server(id, name, name_company, role, phone1, phone2, address, creation_date, creation_user_name, enterprise_id);
                }
            }
            else {
                console.log("No hay contactos que sincronizar");
                Sinchr_schedule();
            }
        }, function(err) {
            console.error(" Error " + err);
        });
    }



    function send_datacontact_server(id, name, name_company, role, phone1, phone2, address, creation_date, create_user_name, enterprise_id) {
        var id_app_contact = id;
        $.ajax({
            type: "POST",
            url: ubication + "send_datacontact_server.php",
            data: ({
                new_name: name,
                new_name_company: name_company,
                new_role: role,
                new_phone1: phone1,
                new_phone2: phone2,
                new_address: address,
                new_creation_date: creation_date,
                new_create_user_name: create_user_name,
                new_enterprise_id: enterprise_id,
				timeout: 25000,
            }),
            async: true,
            success: function(datos) {
                if (datos == 1) {
                    console.log("contacto  "+name + " Subido con id_app => "+id_app_contact+" al Servidor Correctamente ");
                    update_sincro_contact_app(id_app_contact, name, enterprise_id);
                } else {
                    console.log(name + " Ya existe el contacto en el servidor");
                }
            },
            error: function(obj, error, objError) {
                console.error("Error sending gcm to server");
            }
        });
    }


    function update_sincro_contact_app(id_localcontact, name_contact, enter_id) {
        var id_server = null;
        $.ajax({
            type: "POST",
            url: ubication + "get_synchonize_contact.php",
            data: ({
                name_cont: name_contact,
                enterprise_id: enter_id,
            }),
            async: true,
            success: function(datos) {
                var dataJson = eval(datos);

                if (dataJson != null) {
                    for (var i in dataJson) {
                        var get_id_server_contact = dataJson[i].result_id_server;
                        var get_id_company_server = dataJson[i].result_id_company;
                        console.log("ID SERVER OBTENIDO CORRECTAMENTE PARA " +
                                name_contact + " => " + get_id_server_contact +
                                " ID Local de esta contacto => " + id_localcontact +
                                " ID_company => " + get_id_company_server);
                        //actualizar registro
                        Up_Contact_Sinchr(name_contact, get_id_server_contact, get_id_company_server, id_localcontact);
                    }
                } else {
                    console.error("No se pudo obtener el id_server y/o company_id para " + name_contact);
                }
            },
            error: function(obj, error, objError) {
                console.error("Error sending gcm to server");
            }
        });

    }

    function Up_Contact_Sinchr(name_contact, id_server, id_company, id_local) {
        executeSql('UPDATE contact SET id_server = ?, company_id = ?, sincr = ? WHERE id = ?', [id_server, id_company, 1, id_local], function(tx, results) {
            console.log("Contacto => " + name_contact + " Sincronizado su ID_SERVER a "+id_server+" su ID_COMPANY a "+id_company+"  y SINCR a 1 correctamente");            
            //sincroniza las reuniones
           Sinchr_schedule();
        }, function(err) {
            console.error(" Error " + err);
        }); 
    }
 

    function Sinchr_schedule() {
	console.warn("Buscando reuniones para sincronizar ");
        executeSql('SELECT * FROM schedule WHERE sincr = ?', [0], function(tx, results) {
            var len = results.rows.length;
            console.log("Cantidad de citas por sincronizar ante el servidor central => " + len);
            
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    var id_schedule = results.rows.item(i).id;
                    var id_contact_local = results.rows.item(i).id_contact;
                    var create_date = results.rows.item(i).creation_date;
                    var date_start = results.rows.item(i).date_reu_ini;
                    var date_end = results.rows.item(i).date_reu_fin;
                    var meet_efect = results.rows.item(i).reu_efec;
                    var obs = results.rows.item(i).obs;
                    var enterp_id = results.rows.item(i).enterprise_id;
                    var address = results.rows.item(i).address;
                    
                    if(meet_efect==0){
                    	//si la reunion no ha sido tipificada como propuesta
    					data_processing_schedule(id_schedule, id_contact_local, create_date, date_start, date_end, meet_efect, obs, enterp_id,address);
                    }else{
                    	data_processing_schedule_reu_efec(id_schedule, id_contact_local, create_date, date_start, date_end, meet_efect, obs, enterp_id,address);
                    }					   
                }
            }
        }, function error(err) {
            console.error("Error  obteniendo citas por sincronizar " + err);
        });
    }
	
	function data_processing_schedule(id_schedule, id_contact_local, create_date, date_start, date_end, meet_efect, obs, enterp_id, address){
		//executeSql('SELECT name, id_server, company_id FROM contact WHERE id = ?', [id_contact_local], function(tx, results) {
		executeSql('SELECT name, id_server, company_id FROM contact WHERE id = ? OR id_server = ?', [id_contact_local, id_contact_local], function(tx, results) {
            var len = results.rows.length;
            var my_name;
            var my_id_server; 
            var my_company_id;           
           
                for (var i = 0; i < len; i++) {
                    my_name = results.rows.item(i).name;
					my_id_server = results.rows.item(i).id_server;
                    my_company_id = results.rows.item(i).company_id;
					console.log("Nombre Contacto => "+my_name+ " my_id_server => "+my_id_server+" my_company_id => "+my_company_id);					
					send_data_schedule_server(id_schedule, my_id_server, create_date, date_start, date_end, meet_efect, obs, my_company_id, enterp_id, address, nameu_co);
                }
            
        }, function error(err) {
            console.error("Error  obteniendo id_server y company_id" + err);
        });
	}
	
	
	function data_processing_schedule_reu_efec(id_schedule, id_contact_local, create_date, date_start, date_end, meet_efect, obs, enterp_id, address){
		executeSql('SELECT name, id_server, company_id FROM contact WHERE id_server = ?', [id_contact_local], function(tx, results) {
            var len = results.rows.length;
            var my_name;
            var my_id_server; 
            var my_company_id;           
            
                for (var i = 0; i < len; i++) {
                    my_name = results.rows.item(i).name;
					my_id_server = results.rows.item(i).id_server;
                    my_company_id = results.rows.item(i).company_id;
					console.log("Nombre Contacto => "+my_name+ " my_id_server => "+my_id_server+" my_company_id => "+my_company_id);
					
					send_data_schedule_server(id_schedule, my_id_server, create_date, date_start, date_end, meet_efect, obs, my_company_id, enterp_id, address, nameu_co);
                }
            
        }, function error(err) {
            console.error("Error  obteniendo id_server y company_id" + err);
        });
	}

 
  
	// se envia la cita sincronizada al server
    function send_data_schedule_server(id_schedule, id_contact, creation_date, start_time, end_time, reu_efec, observation, company_id, enterprise_id, address, name_user) {
    	$.ajax({
            type: "POST", 
            url: ubication + "send_dataschedule_server.php",
            data: ({
            	new_id_app: id_schedule,
                new_id_contact: id_contact,
                creat_date: creation_date,
                reu_start: start_time,
                reu_end: end_time,
                reu_efec: reu_efec,
                observ: observation,
                new_company_id: company_id,
                enter_id: enterprise_id,
                name_seller: name_user,
                version: version_app,
                address_meet : address, 
            }),  
            async: true,
            success: function(datos) {
                if (datos == 1) {	
                    console.log("Reunion Subida o Actualizada Correctamente al Servidor ");
                    Up_Schedule_Sinchr(id_schedule, id_contact, company_id);
                } 
                else{
                	console.warn("Reunion No Ha Sido Subida o Actualizada Correctamente al Servidor ");
                }
            },
            error: function(obj, error, objError) {
                console.error("Error accediendo a la pagina send_dataschedule_server.php");
            }
        });
    }
	 
    function Up_Schedule_Sinchr(id_schedule, id_contact, company_id) {
        executeSql('UPDATE schedule SET sincr = ?, id_contact = ?, company_id = ? WHERE id = ?', [1, id_contact, company_id, id_schedule], function(tx, results) {
            console.log("Reunion Sincronizada correctamente ante el servidor con id de contacto a "+id_contact+" y id de compaï¿½ia a "+company_id);
        }, function(err) {
            console.error(" Error al intentar sincronizar la reuni\u00f3n. " + err);
        });
    }
	

    function send_datacompany_server(id, name, address, creation_date, create_user_name, enterprise_id) {
        var id_app_company = id;
        $.ajax({
            type: "POST",
            url: ubication + "send_datacompany_server.php",
            data: ({ 
                new_name: name,
                new_address: address,
                new_creation_date: creation_date,
                new_create_user_name: create_user_name,
                new_enterprise_id: enterprise_id,
				timeout: 25000,
            }), 
            async: true,
            success: function(datos) {
                if (datos == 1) {
                    console.log("Compania => "+name + " Subida al Servidor Correctamente");
                    update_sincro_company_app(id_app_company, name);
                } else {
                    console.warn(name + " Ya existe en el servidor");
                }
            },
            error: function(obj, error, objError) {
                console.error("Error accediendo a la pagina send_datacompany_server.php");
            }
        });

    }

    function update_sincro_company_app(id_localcompany, name_company) {
        var id_server = null;
        $.ajax({
            type: "POST",
            url: ubication + "get_synchronize_company.php",
            data: ({
                name_company: name_company,
                enterprise_id: enterprise_ID,
				timeout: 25000,
            }),
            async: true,  
            success: function(datos) {   
                if (datos != null) {
                    id_server = datos;					
                    console.log("ID SERVER OBTENIDO CORRECTAMENTE PARA " + name_company + " => " + id_server + " ID Local de esta compaï¿½ia => " + id_localcompany);
                    //actualizar registro
                    Up_Company_Sinchr(name_company, id_server, id_localcompany);
                } else {
                    console.error("No se pudo obtener el id_server para " + name_company);
                }
            },
            error: function(obj, error, objError) {
                console.error("Error sending gcm to server");
            }
        });
    }

    function Up_Company_Sinchr(name_company, id_server, id_local) {
        executeSql('UPDATE company SET id_server = ?, sincr = ? WHERE id = ?', [id_server, 1, id_local], function(tx, results) {
            console.log("Compania => " + name_company + "  Sincronizado su ID_SERVER a "+id_server);
        }, function(err) {
            console.error(" Error " + err);
        });
    }

    function checkConnection() {
        $.ajax({
            url: ubication + "process.php",
            async: true,
            data: {'tag': 'connection'},
            timeout: 25000,
        })
                .fail(function() {
                    conn = false;
                })
                .done(function() {
                    conn = true;
                })
    }
 
    function clear_list_contact() {
        var listcont = document.getElementById('prof_list_contacts');
        $('#prof_list_contacts option[value!=0]').remove();
        $(listcont).selectmenu().selectmenu('refresh', true);
        console.log("Lista de contactos vaciada ");	
    }
     
  
    $('#contactlist').click(function() {
    	load_list_contact();
    });
    


    /*function getVersioncContact() {
	console.warn("****** Consultando cambios en el servidor para contactos ********");
        executeSql("SELECT version_contact FROM controlapp WHERE id = ?", [1], function Success(tx, results) {
            var len = results.rows.length;
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    version_contact_local = results.rows.item(i).version_contact;
                    console.log("Version Actual Local Contactos " + version_contact_local);
                } // close for
            }//close if
            updatecontact(); 
        }, errorCB);
    }
	
	//obtiene los contactos que no estan sincronizados
	function get_list_contact_to_sincronize(){
		executeSql("SELECT id FROM contact WHERE sincr = ?", [0], function Success(tx, results) {
            var len = results.rows.length;
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    var local_id = results.rows.item(i).id;
                } 
            }
            updatecontact(id_local_app); 
        }, errorCB);
	}*/

    function GetVersioncContact_app() {
        var version_current;
        executeSql("SELECT version_contact FROM controlapp WHERE id = ?", [1], function Success(tx, results) {
            var len = results.rows.length;
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    version_current = results.rows.item(i).version_contact;
                    console.log("Version Local Contactos Actual " + version_current);
                } // close for
            }//close if
            updateversion_contact(version_current);
        }, errorupdate_versionContact);
    }

    function errorupdate_versionContact() {
        console.error("Error obteniendo version local de version_contact");
    }

    function GetVersioncCompany_app() {
        var version_current;
        executeSql("SELECT version_company FROM controlapp WHERE id = ?", [1], function Success(tx, results) {
            var len = results.rows.length;
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    version_current = results.rows.item(i).version_company;
                    console.log("Version Local Companias " + version_current);										
                } 
            }
            updateversion_company(version_current);
        }, errorCB_addVersioncCompany);
    }

    function errorCB_addVersioncCompany() {
        console.error("Error agregando nueva version local de compaï¿½ia");
    }

    function getVersioncCompany() {
        executeSql("SELECT version_company FROM controlapp WHERE id = ?", [1], function Success(tx, results) {
            var len = results.rows.length;
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    version_company_local = results.rows.item(i).version_company;
                    console.log("Version actual de Compaï¿½ias Local " + version_company_local);
                } 
            }
            updatecompany();
        }, errorCB);
        get_enterprise_id_compa();
    }


    function get_enterprise_id_compa() {
        executeSql("SELECT enterprise_id FROM controlapp WHERE id = ?", [1], function Success(tx, results) {
            var len = results.rows.length;
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    enterprise_ID = results.rows.item(i).enterprise_id;
                    console.log("enterprise_ID Obtenido para companias:  " + enterprise_ID);					
                }
                getVersioncCompany();
            } else {
                console.error("enterprise_ID No found ");
            }

        }, errorCB);
    }

/* function updatecontact() {
        var value_sincron = 1;
        $.ajax({
            type: "POST",
            url: ubication + "controlversion_contact.php",
            data: ({
                version_cont_app: version_contact_local,
                enterprise: enterprise_ID,
                timeout: 25000, 
            }),
            async: true,
            success: function(datos) {
                var dataJson = eval(datos);
                for (var i in dataJson) {

                    //se obtiene el id del contacto en el servidor																		
                    var id_contact = dataJson[i].my_id_contact;

                    //se le asigna el mismo id del contacto del servidor al contacto local, 																		
                    var id = dataJson[i].my_id_contact;
                    //console.log("id_contact " +id_contact);

                    var id_company = dataJson[i].my_id_company;
                    //console.log("id_company " +id_company);																	

                    var name_contact = dataJson[i].my_name;
                    //console.log("name_contact " +name_contact);

                    var role_contact = dataJson[i].my_role;
                    //console.log("role_contact " +role_contact);   

                    var phone1_contact = dataJson[i].my_phone1;
                    //console.log("phone1_contact " +phone1_contact);	 																	
 
                    var phone2_contact = dataJson[i].my_phone2;
                    //console.log("phone2_contact " +phone2_contact);  

                    var address_contact = dataJson[i].my_address;
                    //console.log("address_contact " +address_contact);
                    
                    var creation_date = dataJson[i].my_creation_date;
                    //console.log("creation_date " +creation_date);

                    var create_user_name = dataJson[i].my_create_user_name;
                    //console.log("create_user_name " +create_user_name);

                    var enterprise_id = dataJson[i].my_enterprise_id;
                    //console.log("enterprise_id " +enterprise_id);

                    var name_compa = dataJson[i].my_name_company;
                    //console.log("name_compa " +name_compa);

                    var version_contact_server = dataJson[i].my_version_server;
                    //console.log("version_contact_server " +version_contact_server);

                    insert_or_update_contact(id_contact, id_company, name_compa, name_contact, role_contact, phone1_contact, phone2_contact, address_contact, creation_date, create_user_name, enterprise_id, value_sincron);

                    updateversion_contact(version_contact_server);

                }
            }, error: function(obj, error, objError) {
            }
        });//close ajax   

    }*/
//executeSql('contact (id, id_server , company_id , name_company ,  name , role , phone1 , phone2 , address , creation_date , creation_user_name , enterprise_id , sincr )', [], CreateTableSuccess, CreateTableError);	

    function clear_table_contact() {
        executeSql('DELETE FROM contact WHERE sincr != ?', [0], function(tx, results) {
            console.log("registros reseteados temporalmente de la tabla contact");
        }, function(err, results) {
        });
    }

    function updatecompany() {
        $.ajax({
            type: "POST",
            url: ubication + "controlversion_company.php",
            data: ({
                version_company_app: version_company_local,
                enterprise: enterprise_ID,
				timeout: 25000,
            }),
            async: true,
            success: function(datos) {

                var dataJson = eval(datos);
                for (var i in dataJson) {

                    var id = dataJson[i].my_id_company;
                    var id_company_server = dataJson[i].my_id_company;
                    var name_company = dataJson[i].my_name_company;
                    var address_company = dataJson[i].my_address_company;
                    var creation_date_company = dataJson[i].my_creation_date;
                    var create_user_name_company = dataJson[i].my_create_user_name;
                    var enterprise_id_company = dataJson[i].my_enterprise_id;
                    var my_version_server_company = dataJson[i].my_version_server_com;

                    insert_or_update_company(id_company_server, name_company, address_company, creation_date_company, create_user_name_company, enterprise_id_company);

                    updateversion_company(my_version_server_company);
                }
            }, error: function(obj, error, objError) {
            }
        });
    }

    function insert_or_update_contact(id_contact, id_company, name_company, name_contact, role_contact, phone1_contact, phone2_contact, address_contact, creation_date, create_user_name, enterprise_id, sincronized) {
		executeSql('SELECT * FROM contact WHERE id_server = ?', [id_contact], function(tx, results) {//success function
            var len = results.rows.length;
            if (len == 0) {
			console.info("Insertando nuevo contacto");
                executeSql("INSERT INTO contact (id_server, company_id, name_company, name, role, phone1, phone2, address, creation_date, creation_user_name, enterprise_id, sincr) " + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?);",
                        [id_contact, id_company, name_company, name_contact, role_contact, phone1_contact, phone2_contact, address_contact, creation_date, create_user_name, enterprise_id, sincronized], function Success(tx, results) {
                    
                    console.log("Registro descargado correctamente desde el servidor ");
                }, function error(err) {
                    console.error("Error descargado registro desde el server " + err);
                });
            } else {    
			console.info("Actualizando contacto");			
                executeSql("UPDATE contact SET company_id = ?, name_company = ?, name = ?, role = ?, phone1 = ?, phone2 = ?, address = ?, creation_date = ?, creation_user_name = ?," + "enterprise_id = ?, sincr = ?  WHERE id_server = ?",
                        [id_company, name_company, name_contact, role_contact, phone1_contact, phone2_contact, address_contact, creation_date, create_user_name, enterprise_id, sincronized, id_contact], function Success(tx, results) {
                    console.log("Registro Sincronizado correctamente con el servidor ");
                }, function error(err) {
                    console.error("Error Sincronizado registro desde el server " + err);
                });	
            }
        }, errorfunction);
    }


    function insert_or_update_company(id_server, name, address, creation_date, create_user_name_company, enterprise_id, sincr) {
    console.log("Insert Or Update Company => "+name);
        executeSql('SELECT * FROM company WHERE id_server = ?', [id_server], function(tx, results) {//success function
            var len = results.rows.length;

            if (len == 0) {
                executeSql("INSERT INTO company (id_server, name, address, creation_date, create_user_name, enterprise_id, sincr) " +
                        " VALUES(?,?,?,?,?,?,?);", [id_server, name, address, creation_date, create_user_name_company, enterprise_id, 1], function Success(tx, results) {
                    console.log("Registro compaï¿½ias descargado correctamente desde el servidor ");

                }, function error(err) {
                    console.error("Error descargado registro de compaï¿½ias desde el server " + err);
                });
            } else {
                executeSql("UPDATE company SET id_server = ?, name = ?, address = ?, creation_date = ?, create_user_name = ?, enterprise_id = ?, sincr = ? WHERE id = ?",
                        [id_server, name, address, creation_date, create_user_name_company, enterprise_id, 1, id_server], function Success(tx, results) {
                    console.log("Registro de compaï¿½ias Sincronizado correctamente con el servidor ");

                }, function error(err) {
                    console.error("Error Sincronizado registro de compaï¿½ias desde el server " + err);
                }); 
            } 
        }, errorfunction);

    }

    function load_list_contact() {
        var listcont = document.getElementById('prof_list_contacts');
        $('#prof_list_contacts option[value!=0]').remove();
        console.log("Vaciando la lista de Contacto ");
        executeSql('SELECT * FROM contact', [], function(tx, results) {
            var len = results.rows.length;
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    var nom = results.rows.item(i).name;
                    var id_cont = results.rows.item(i).id;
                    console.log("Agregando a lista de contactos a:  " + nom + " ID de Contacto " + id_cont);
                    $(listcont).append('<option value=' + id_cont + '>' + nom + '</option>');
                }
                $(listcont).selectmenu().selectmenu('refresh', true);
            }
        }, function error(err) {
            console.error("Error  " + err);
        });

    }

    function load_list_company() {
        var listcomp = document.getElementById('list_companies');
        $('#list_companies option[value!=0]').remove();       
        
        executeSql('SELECT id, name FROM company group by name', [], function(tx, results) {
            var len = results.rows.length;
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    var nom_com = results.rows.item(i).name;
                    var id = results.rows.item(i).id;
                    console.log("Agregando a lista de companias => :  " + nom_com);
                    $(list_companies).append('<option value=' + id + '>' + nom_com + '</option>');
                }
                	$(list_companies).selectmenu().selectmenu('refresh', true);
            } else {
                console.log("La Lista de compaï¿½ias esta vacia.");
            }
        }, function error(err) {
            console.error("Error  " + err);
        });
	sinchonized_contact();
    }

    function errorfunction(err) {
        console.log("Error " + err);
    }

    // event for set and display elements in page (index_co)
    $(document).on('pagebeforeshow', '#index_co', function(event) {
    	//trae el nombre del vendedor para mostrar mensaje de bienvenida
        queryUpdatenameco(); 
        //consulta si debe resetear el contador de llamadas
        get_date_last_call(); 
        $("#saludo").html("Bienvenido " + nameu_co);
        load_list_contact();
        event.preventDefault();
    })
 
    
    function get_last_address_meeting(id_contact){
    	executeSql('select address from schedule where id_contact = ? order by date_reu_ini Desc', [id_contact], function(tx, results) {
    	var len = results.rows.length;
    	$('#address_contact').val("");
    		if (len > 0) {
                for (var i = 0; i < len; i++) {
                	last_address_meeting = results.rows.item(i).address; 
                	$('#address_contact').val(last_address_meeting);
                }      
            } else {
                console.log("No tiene reuni\u00f3n anterior de reuniones");
            }   		
            }, function error(err) {
                console.error("Error obteniendo direcci\u00f3n de reuni\u00f3n anterior");
            });
    } 
    
    function setDisplayDataUser(user) {
        executeSql('SELECT a.id, a.id_server, a.company_id, a.name_company, a.name, a.phone1, a.phone2, a.role FROM contact a LEFT JOIN company b ON a.company_id = b.id_server where a.name = ?', [user], querySetDisplaySuccessUser, errorCB);
    }
   
    function querySetDisplaySuccessUser(tx, results) {
    	var my_idc=null;    	
        var len = results.rows.length;

        if (len == 0) {
            console.error("Usuario " + convalue + " no se encontro en la tabla contactos.");
        } else {
            for (var i = 0; i < len; i++) {
            	my_idc = results.rows.item(i).id_server;
            	//if no ha sido sincronizado y el id_server es cero
            	if(my_idc == 0 || my_idc == null){
            		my_idc = results.rows.item(i).id;
            	}
            	get_last_address_meeting(my_idc);
            		
 
                //muestra los valores en la pagina de crear una reunion.
                $('#tel_fix').val(results.rows.item(i).phone1);
                $('#tel_cel').val(results.rows.item(i).phone2);
                $('#posit_contact').val(results.rows.item(i).role);
                
                $('#list_companies option').filter(function() {
                    return $(this).html() == results.rows.item(i).name_company;
                }).prop('selected', true);
                $('#list_companies').selectmenu("refresh", true);
                ID_contact = results.rows.item(i).id;
            }
        }
    }

    // event for schedule reunion and add an contact from page schedule
    $('#conf_reu').click(function() {
    	$("#div_conf_reu").css("display", "none");
        company = $("#list_companies option:selected").text();
 
        phone_fix = $("#tel_fix").val();
        phone_cel = $("#tel_cel").val();
        position_contact = $("#posit_contact").val();
        date_quote = $("#date_quote").val();
        hour_qoute = $("#hour_quote").val();
        address = $("#address_contact").val();
        data_create_cont = datenow;
        hour_qoute_fin = $("#hour_fin_quote").val();
		var hour_ini = date_converter2(hour_qoute);
		new_dateini = date_quote+" "+hour_ini;
		var hour_end = date_converter2(hour_qoute_fin);
		new_date_final = date_quote+" "+hour_end;
		obs_quot = $("#obs_quote").val();
		
		
		var h1 = hour_ini.substring(0, 2);
		var h2 = hour_end.substring(0, 2);
		var hc = currentDate.getHours();
		
		var daycurrent = ""+day;
		var monthcurrent = ""+month;
		var hourcurrent = ""+hc;
		
		if(daycurrent.length==1){
			daycurrent = "0"+day;
		} 
		  
		if(monthcurrent.length==1){
			monthcurrent = "0"+month;
		}
		
		if(hourcurrent.length==1){
			hourcurrent = "0"+hourcurrent;
		}
 
		
		var fech_current_new = year + "-" + monthcurrent + "-" + daycurrent;
		if(company != "Seleccione una empresa" && person_judirica == 1 || ctrl_new_to_presave == 2){

			if(date_quote.length > 0){
	
				if(hour_ini.length > 0){

					if(hour_qoute_fin.length > 0){
	
						if(Date.parse(date_quote) == Date.parse(fech_current_new)){
			
							if(h1 == h2){
								Dialog("la hora de inicio y la final son iguales!", function(){}, "error");
								$("#div_conf_reu").css("display", "block");
								return false;
							}
							
							else if(h1 < hourcurrent){
								Dialog("Hora  inicio es menor o igual a la hora actual!", function(){}, "error");
								$("#div_conf_reu").css("display", "block");
								return false;
							}
							
							else if(h1 > h2){
								Dialog("la hora de inicio es mayor a la hora final!", function(){}, "error");
								$("#div_conf_reu").css("display", "block");
								return false;
							}
							
							else {		
								confirmDialog(" Desea agendar esta reuni\u00f3n ahora? ", function(){
									
									getDataUserExist(convalue);
								});
								
							}
	
							
						} else if(Date.parse(date_quote) <= Date.parse(fech_current_new)){
							Dialog("El inicio de la reuni\u00f3n es anterior a la fecha actual!", function(){}, "error");
							$("#div_conf_reu").css("display", "block");
							return false;
						} 
						  else{
							  
							  if(h1 == h2){
									Dialog("la hora de inicio y la final son iguales!", function(){}, "error");
									$("#div_conf_reu").css("display", "block");
									return false;
								}
							   
							  else if(h1 > h2){
									Dialog("la hora de inicio es mayor a la hora final!", function(){}, "error");
									$("#div_conf_reu").css("display", "block");
									return false;
								}
							  
							  else {
								  confirmDialog(" Desea agendar esta reuni\u00f3n ahora? ", function(){
									
									  getDataUserExist(convalue);
									});
								}						
						  }
					}else{
							Dialog("Debe seleccionar una hora final valida!", function(){}, "error");
							$("#div_conf_reu").css("display", "block");
							return false;
					}
											
				}else{					
					Dialog("Debe seleccionar una hora de inicio valida!", function(){}, "error");
					$("#div_conf_reu").css("display", "block");
					return false;
				}
												
			}else{
				Dialog("Debe seleccionar una fecha valida!", function(){}, "error");
				$("#div_conf_reu").css("display", "block");
				return false;
			}
	
		}//cierre de persona juridica
		
		//opcion persona natural
		else if(person_natural == 1){
			confirmDialog(" El nuevo contacto es una persona natural, y no tendra asociada ninguna empresa desea continuar? ", function(){	
	        	if(date_quote.length > 0){
				
				if(hour_ini.length > 0){
 
					if(hour_qoute_fin.length > 0){
	
						if(Date.parse(date_quote) == Date.parse(fech_current_new)){
			
							if(h1 == h2){								
								Dialog("la hora de inicio y la final son iguales!", function(){}, "info");
								$("#div_conf_reu").css("display", "block");
								return false;
							}
							
							else if(h1 < hourcurrent){
								Dialog("Hora  inicio es menor o igual a la hora actual!", function(){}, "info");
								$("#div_conf_reu").css("display", "block");
								return false;
							}
							
							else if(h1 > h2){
								Dialog("la hora de inicio es mayor a la hora final!", function(){}, "info");
								$("#div_conf_reu").css("display", "block");
								return false;
							}
							
							else {								
								confirmDialog(" Desea agendar esta reuni\u00f3n ahora? ", function(){
									
									getDataUserExist(convalue);
								});
							}
	
							
						} else if(Date.parse(date_quote) <= Date.parse(fech_current_new)){
							Dialog("El inicio de la reuni\u00f3n es anterior a la fecha actual!", function(){}, "info");
							$("#div_conf_reu").css("display", "block");
							return false;
						} 
						  else{
							  
							  if(h1 == h2){
									Dialog("la hora de inicio y la final son iguales!", function(){}, "info");
									$("#div_conf_reu").css("display", "block");
									return false;
								}
							   
							  else if(h1 > h2){
									Dialog("la hora de inicio es mayor a la hora final!", function(){}, "info");
									$("#div_conf_reu").css("display", "block");
									return false;
								}
							   
							  else {
								  confirmDialog(" Desea agendar esta reuni\u00f3n ahora? ", function(){
									 
									  getDataUserExist(convalue);
									});
								}						
						  }
					}else{
							Dialog("Debe seleccionar una hora final valida!", function(){}, "info");
							$("#div_conf_reu").css("display", "block");
							return false;
					}
											
				}else{
					Dialog("Debe seleccionar una hora de inicio valida!", function(){}, "info");
					$("#div_conf_reu").css("display", "block");
					return false;
				}
												
			}else{
				Dialog("Debe seleccionar una fecha valida!", function(){}, "info");
				$("#div_conf_reu").css("display", "block");
				return false;
			}
	      });
	    	  $("#div_conf_reu").css("display", "block");  
	       //	cierre respuesta persona juridica
		}//cierre if persona juridica
		
		else{
			Dialog("Debe asociar una empresa para una persona juridica!", function(){}, "info");
			$("#div_conf_reu").css("display", "block");
			return false;
		}	
    });
		
		
	function date_converter2(parse_date) {
        var date_converter;
        var cant_total = parse_date.length;//16

        var get_time = parse_date.substring(cant_total - 2, cant_total);
        if (get_time == "PM") {
            
		var d1 = parse_date.substring(0, 2);
		var d2 = parse_date.substring(3, 5);
		
            if (d1 != '12' ) {
			
				var dx = parse_date.substring(0, 1);
				var dx2 = parse_date.substring(1, 2);
					if(dx==0){
						var to_number = parseInt(dx2);
					}else{
						var to_number = parseInt(d1);
					}
				var d1f = to_number + 12;
				
			date_converter = d1f.toString() + ":" + d2;
			
               
            } else {
            	date_converter = d1 + ":" + d2; 
            }

        } else {
		
			var sdf = parse_date;
			var cant_total = parse_date.length;//8
			var new_data = sdf.substring(0, cant_total-3);
			
            date_converter = new_data;
			
        }
        return date_converter;
    }
	
	
	
	
	    function date_converter(parse_date) {
        var date_converter;
        var cant_total = parse_date.length;

        var get_time = parse_date.substring(cant_total - 2, cant_total);
        if (get_time == "PM") {
            var d1 = parse_date.substring(0, 2);
            var d2 = parse_date.substring(3, 5);

            if (d1 != '12') {
                var d1_to_number = parseInt(d1);
                var d1f = d1_to_number + 12;
                date_converter = d1f.toString() + ":" + d2 + " " + get_time;
            } else {
                date_converter = parse_date;
            }

        } else {
            date_converter = parse_date;
        }
        return date_converter;
    }

	
	//actualiza el campo de id_server en compaï¿½ia
	function setId_local_company(new_id_server){
		executeSql('UPDATE company SET id_server = ? WHERE id = ?', [new_id_server, new_id_server], function(tx, results) {
        console.log("Actualizado Correctamente el id de la compaï¿½ia");  
		 
        }, function error(err) {
            console.error("Error Seteando id_server a compaï¿½ia.");
        });
	}

    function UpdateVersionServer() {
        $.ajax({
            type: "POST",
            url: ubication + "ctrlv_contact_to_server.php",
            data: ({
                version_cont_app: version_contact_local,
                enterprise: enterprise_ID,
				timeout: 25000,
            }),
            async: true,
            success: function(datos) {
                var dataJson = eval(datos);
                for (var i in dataJson) {
                    var status = dataJson[i].status;
                    console.log("status " + status);
                }
            },
            error: function(obj, error, objError) {
            	console.log("status " + status);
            }
        });
    }

    function QinsertContactSuccess() {
        console.log("Query success insertContact");
    }
  
    function errorCB(err) {
        console.error("Error processing SQL: " + err);
    }
    
    function getIdCompanyoffline(name_company) {
        executeSql("SELECT id FROM company WHERE name = ?", [name_company], function(tx, results) {
            console.log("Buscando ID de la Compania "+name_company);
            var len = results.rows.length;
			
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                	ID_Company = results.rows.item(i).id;
                	console.log("ID de compania obtenido => " + ID_Company);
                	if(ctrl_new_to_presave == 1){
                		db.transaction(insertContact, QinsertContactSuccess, errorCBinsertContact);
                	}else{	
                		db.transaction(queryDisponibility, errorCBDisponibility);
                	}	 
                }
            }        
			else{
				console.warn("No se encontro ID para Compania");
			}
                    
        }, function(err) {
            console.error(" Error " + err);
        });
    } 
 
    function insertContact(tx, results) {
        tx.executeSql('INSERT INTO contact (id_server, company_id, name_company, name, role,  phone1, phone2, address, creation_date, creation_user_name, enterprise_id, sincr) values (?,?,?,?,?,?,?,?,?,?,?,?);',
                [0, ID_Company, company, convalue, position_contact, phone_fix, phone_cel, address, data_create_cont, nameu_co, enterprise_ID, 0], insertSuccessContact, errorInsertContact);
    }
 
    function errorInsertContact(error) {
        console.error("Error Insertando Contacto " + error.code);
    }

    function insertSuccessContact() {
        var id = '1'; 
       // var data_create_com = datenow + " 00:00:00";
        var data_create_com = datenow;
        var listcont = document.getElementById('prof_list_contacts');
        console.log("Nuevo contacto insertado correctamente");

		db.transaction(queryID, errorQueryID);
    }  
  
    function errorQueryID() {
        console.error(" Error obteniendo el ID del contacto. " + err);
    }

    function queryID(tx, results) {
        tx.executeSql('SELECT * FROM contact where name = ?', [convalue], querySuccessUserID, miError);
    }

    function miError(err) {
        console.error("Error Insertando Nuevo Contacto" + err.code);
    }

    function querySuccessUserID(tx, results) {
        var len = results.rows.length;
        //consultando el ultimo contacto insertado, para obtener su ID
        if (len > 0) {
            for (var i = 0; i < len; i++) {  
                ID_contact = results.rows.item(i).id;
                console.log("Ultimo Contacto Se le asigno ID local => " + ID_contact);
                setId_localserver(ID_contact)
            }
 
        } else {
            if (ctrl_new_to_presave == 1) {
                console.error("Ultimo ID de usuario creado, No Encontrado ");
            }
        }
   
    }
	

	//actualiza el campo de id_server en contacto
	function setId_localserver(new_id_server){
		executeSql('UPDATE contact SET id_server = ? WHERE id = ?', [new_id_server, new_id_server], function(tx, results) {
          console.log("Actualizacion provisional correcta del id_server del contacto");
		 db.transaction(queryDisponibility, errorCB);  
        }, function error(err) {
            console.error("Error Setenado id_server a contato.");
        });
	}
	
    function getDataUserExist(user) {
        executeSql('SELECT * FROM contact where name = ?', [user], querySuccessUser, errorCBgetNameContact);
    }
    
    function getIdlocalCompany(name_company){
        
        executeSql("SELECT id from company where name =?",[name_company], function Success(tx, results) {				
    			var len = results.rows.length;
    			if(len > 0){
    				for (var i = 0; i < len; i++) {
    					ID_Company = results.rows.item(i).id; 
                    }   				
    				db.transaction(insertContact, QinsertContactSuccess, errorCBinsertContact);	
    			}
                
            }, errorCB);	
        }
    
    
    function querySuccessUser(tx, results) {
        var len = results.rows.length;

        console.log("Buscando el usuario " + convalue+ " en la tabla contactos");
  
        if (len == 0) {   
            console.log("Usuario " + convalue + "  no se encontro en la tabla contactos");
            //if the contact is new, and not exist in the list of contact is add
            if (ctrl_new_to_presave == 1) {
                console.log("Es nuevo, y no exite: voy a insertarlo en la tabla contactos");
                 
                if(person_natural == 1){
                	company = "Personal";
                	ID_Company = 0;
                	db.transaction(insertContact, QinsertContactSuccess, errorCBinsertContact);
                }else if(person_judirica == 1){
                	getIdlocalCompany(company);
                }   
            }            
 
        } else {
            for (var i = 0; i < len; i++) { 
                console.log("Usuario existente");
                
                //set values of user exist in the page specify
                $('#tel_fix').val(results.rows.item(i).phone1);
                $('#tel_cel').val(results.rows.item(i).phone2);
                $('#posit_contact').val(results.rows.item(i).role);
                $('#address_contact').val(results.rows.item(i).address);
                $('#list_companies option').filter(function() {
                					return $(this).html() == results.rows.item(i).name_company;
                				}).prop('selected', true); 
                $('#list_company').selectmenu("refresh", true);
                ID_contact = results.rows.item(i).id;
                ID_Company = results.rows.item(i).company_id;

                db.transaction(queryDisponibility, errorCB); 
                //--getIdCompanyoffline(company);
                
            }
        }

    }

    function errorCBgetNameContact(tx) {
        console.error("Error obteniendo nombre de contacto");
    }

    function errorCBinsertContact(tx) {
      console.error("Error insertanta nombre de contacto");
    }

    function queryDisponibility(tx) {
        tx.executeSql('SELECT * FROM schedule', [], querySuccessDisponibility, errorCBDisponibility);
    }

    function errorCBDisponibility() {
        console.error("Error consultando citas");
    }
 
    function querySuccessDisponibility(tx, results) {
        var len = results.rows.length;
        console.log("Cantidad de citas " + len);
 
        //si la agenda tiene reuniones
        if (len > 0 ) { 
            for (var i = 0; i < len; i++) {
                console.log(
                        "Id Contacto = " + results.rows.item(i).id_contact+ "   Date Reunion = " + results.rows.item(i).date_reu_ini + " Hour End = " + results.rows.item(i).date_reu_fin +" Efectiva = " + results.rows.item(i).reu_efec + " Observaciones = " + results.rows.item(i).obs +" Id Contacto = " + results.rows.item(i).id_contact + " Company ID = " + results.rows.item(i).company_id + " Sinchronized = " + results.rows.item(i).sincr);
            } 
            db.transaction(queryavailable, errorCB);
        }
        // si la agenda no tiene reuniones, o es la primera reunion del dia
        else {
            console.log("La agenda esta vacia, o es la primea reuni\u00f3n del dia");
            tx.executeSql('INSERT INTO schedule (id_contact, creation_date, date_reu_ini, date_reu_fin, reu_efec, obs, company_id, enterprise_id, sincr, address, meeting_re) values (?,?,?,?,?,?,?,?,?,?,?);',
                    [ID_contact, datenow, new_dateini, new_date_final, 0, obs_quot, ID_Company, enterprise_ID, 0, address, 0], insertSuccessNewQuote, errorCB);
        }
    }


    function queryavailable(tx) {
        tx.executeSql("SELECT * FROM schedule WHERE julianday(date_reu_ini) BETWEEN julianday(" +
        "'" + new_dateini + "')" + " AND julianday(" + "'" + new_date_final + "')" +
        "OR julianday(date_reu_fin) BETWEEN julianday(" + "'" + new_dateini + "')" +
        " AND julianday(" + "'" + new_date_final + "')", [], queryavailableSuccess, errorCB);

    }

    function queryavailableSuccess(tx, results) {

        var len = results.rows.length;
        console.log("Concordancias " + len);

        if (len > 0) {
            console.log("Cita Ya Asignada ");
            Dialog("La hora seleccionada ya se encuntra asignada a otra cita!", function(){}, "error");
            return false;
            for (var i = 0; i < len; i++) {
                console.log( "Id Contacto = " + results.rows.item(i).id_contact + "   Date Start Reunion = " + results.rows.item(i).date_reu_ini + " Date Final Reunion = " + results.rows.item(i).date_reu_fin + " Efectiva = " + results.rows.item(i).reu_efec + " Observaciones = " + results.rows.item(i).obs);
            }
        } else {
            tx.executeSql('INSERT INTO schedule (id_contact, creation_date, date_reu_ini, date_reu_fin, reu_efec, obs, company_id, enterprise_id, sincr, address, meeting_re) values (?,?,?,?,?,?,?,?,?,?,?);',
                    [ID_contact, datenow, new_dateini, new_date_final, 0, obs_quot, ID_Company, enterprise_ID, 0, address, 0], insertSuccessNewQuote, errorCB);
        }
    }
    
    
    

    function insertSuccessNewQuote() {
        console.log("Nueva Reunion Insertada Correctamente");
        $.mobile.changePage("#index_co");
        //	comienza a realizar la sincronizacion ante el servidor una vez a finalizado de crear la nueva reunion      
        //--sinchonized_company(); 
    }


    function proccessDateFomat(date) {
        var elem = date.split('-');
        var anio = elem[0];
        var mes = elem[1];
        if (mes.length == 1) {
            mes = "0" + mes;
        }

        var dia = elem[2];
        if (dia.length == 1) {
            dia = "0" + dia;
            $.mobile.changePage("#qoute");
        }
    }
    
    
    function getIdlocalCompany_reschedule(name_company){   
        executeSql("SELECT id from company where name =?",[name_company], function Success(tx, results) {				
    			var len = results.rows.length;
    			if(len > 0){
    				for (var i = 0; i < len; i++) {
    					ID_Company = results.rows.item(i).id_server; 
                    }
    			}
    			 executeSql('SELECT * FROM schedule', [], querySuccessDisp_reschedulle, errorCB);
            }, errorCB);	
    }
 
    $('#saveq').click(function() {
        //obtenemos las observaciones y la fecha de la cita
        my_obs = $("#obs_go_quote").val();
        var date_quote_total = $("#date_go_quote").val();
        company = $("#name_company_quote").val(); 
        //************ Hora Inicio *******************
        address_schedule = $("#address_meeting").val();
        var re_hour = date_converter($("#hour_re_quote").val());
        var data_ini = date_quote_total + " " + re_hour;
        fi_data_am = data_ini.substring(0, data_ini.length - 3);
        
        //************ Hora Fin *******************
        var new_hour_pm = date_converter($("#hour_fin_re_quote").val());      
        var data_finpm = date_quote_total + " " + new_hour_pm;       
        fi_date_pm = data_finpm.substring(0, data_finpm.length - 3);
        
        var h1 = re_hour.substring(0, 2);
		var h2 = new_hour_pm.substring(0, 2);
		var hc = currentDate.getHours();
		
		var daycurrent = ""+day;
		var monthcurrent = ""+month;
		var hourcurrent = ""+hc;
		
		if(daycurrent.length==1){
			daycurrent = "0"+day;
		} 
		  
		if(monthcurrent.length==1){
			monthcurrent = "0"+month;
		}
		
		if(hourcurrent.length==1){
			hourcurrent = "0"+hourcurrent;
		}

		//obtenemos la fecha actual
		var fech_current_new = year + "-" + monthcurrent + "-" + daycurrent;
		
		confirmDialog(" Desea Guardar los datos de esta reuni\u00f3n ", function(){
			if (date_quote_total.length > 0 && fi_data_am.length > 0 && fi_date_pm.length > 0) {
            	
            	if(Date.parse(date_quote_total) == Date.parse(fech_current_new)){
            		
            		if(h1 == h2){
						Dialog("la hora de inicio y la final son iguales!", function(){}, "info");
						return false;
					}
					
					else if(h1 < hourcurrent){
						Dialog("Hora  inicio no puede ser menor o igual a la hora actual!", function(){}, "info");
						return false;
					}
					
					else if(h1 > h2){
						Dialog("la hora de inicio no puede ser mayor a la hora final!", function(){}, "info");
						return false;
					}
					
					else {
						//si la cita esta marcada como propuesta, y el chkbox no esta marcado
						if(status_proposal == 1 && chk_status_reu_efect == 0){
							confirmDialog(" Esta Reunion fue tipificada como propuesta anteriormente, Seleccione ACEPTAR para continuar y cambiar el estado actual a No Propuesta, O CANCELAR si desea marcarla como propuesta? ", function(){
					        	//continua consultando la disponibilidad de las citas
								executeSql('SELECT * FROM schedule', [], querySuccessDisp_reschedulle, errorCB);
					        });
						}else{
							//continua consultando la disponibilidad de las citas
							executeSql('SELECT * FROM schedule', [], querySuccessDisp_reschedulle, errorCB);
						}  
					}
            	}
            	
            	 
            	if(Date.parse(date_quote_total) > Date.parse(fech_current_new)){
            		if(h1 == h2){
						Dialog("la hora de inicio y la final son iguales!", function(){}, "info");
						return false;
					}
            		
            		else if(h1 > h2){
						Dialog("la hora de inicio no puede ser mayor a la hora final!", function(){}, "info");
						return false;
					}
            		  
            		else{
            			//continua consultando la disponibilidad de las citas
            			//si la cita esta marcada como propuesta, y el chkbox no esta marcado
						if(status_proposal == 1 && chk_status_reu_efect == 0){
							confirmDialog(" Esta cita fue tipificada como propuesta anteriormente, Seleccione ACEPTAR para continuar y cambiar el estado actual a No Propuesta, O CANCELAR si desea marcarla como propuesta? ", function(){
					        	//continua consultando la disponibilidad de las citas
					        	executeSql('SELECT * FROM schedule', [], querySuccessDisp_reschedulle, errorCB);
					        });
						}else{
							//continua consultando la disponibilidad de las citas
				        	executeSql('SELECT * FROM schedule', [], querySuccessDisp_reschedulle, errorCB);
						}	
					}
            	}
            	else if(Date.parse(date_quote_total) < Date.parse(fech_current_new)){
            		Dialog("La fecha seleccionada es menor a la fecha actual!", function(){}, "info");
					return false;
            	}
                   
            }
         
            //si no se ingresa informacion en los campos para un re agendamiento
            else{
				
			//solo actualiza la reunion	
            if(status_proposal == 1 && chk_status_reu_efect == 0){
            	confirmDialog(" Esta Reunion fue tipificada como propuesta anteriormente, Seleccione ACEPTAR para continuar y cambiar el estado actual a No Propuesta, O CANCELAR si desea marcarla como propuesta? ", function(){
			        	//continua consultando la disponibilidad de las citas
			        	executeSql('UPDATE schedule SET reu_efec = ?, address = ?, obs = ?, sincr = ? WHERE id = ?', 
			            [chk_status_reu_efect, address_schedule, my_obs, 0, id_quote_schedule], UpSuccess, errorCB);
			        });
			}else{
					//continua consultando la disponibilidad de las citas
					executeSql('UPDATE schedule SET reu_efec = ?, address = ?, obs = ?, sincr = ? WHERE id = ?', 
				            [chk_status_reu_efect, address_schedule, my_obs, 0, id_quote_schedule], UpSuccess, errorCB);
			}	
		}	 
			 
		 });
       
    });

    function UpSuccess() {
        console.log("Reunion  Actualizada Correctamente");
        $.mobile.changePage("#index_co");
    }

    $('#save_and_send').click(function() {
        var data_of_register;
        my_obs = $("#obs_go_quote").val();
        address_schedule = $("#address_meeting").val();
        var date_quote_total = $("#date_go_quote").val();
        var re_hour = $("#hour_re_quote").val();
        var new_hour_am = date_converter(re_hour);

        var data_ini = date_quote_total + " " + new_hour_am;
        var cant = data_ini.length;
        var parse_date_ini = data_ini.substring(0, cant - 3);
        fi_data_am = parse_date_ini + ":00";

        var re_hourpm = $("#hour_fin_re_quote").val();
        var new_hour_pm = date_converter(re_hourpm);
        var data_finpm = date_quote_total + " " + new_hour_pm;
        var can2 = data_finpm.length;
        var parse_date_fipm = data_finpm.substring(0, can2 - 3);
        fi_date_pm = parse_date_fipm + ":00";
        
        confirmDialog(" Desea Guardar los datos de esta reuni\u00f3n y pasar a venta? ", function(){
            status_pass_to_sale = 1;
            if(status_proposal == 1 && chk_status_reu_efect == 0){
            	confirmDialog(" Esta Reunion fue tipificada como propuesta anteriormente, Seleccione ACEPTAR para continuar y cambiar el estado actual a No Propuesta, O CANCELAR si desea marcarla como propuesta? ", function(){
		        	executeSql('UPDATE schedule SET reu_efec = ?, address = ?, obs = ?, sincr = ? WHERE id = ?', [chk_status_reu_efect, address_schedule, my_obs, 0, id_quote_schedule], UpSuccess2, errorCB);
		        });
			}else{				
	        	executeSql('UPDATE schedule SET reu_efec = ?, address = ?, obs = ?, sincr = ? WHERE id = ?', [chk_status_reu_efect, address_schedule, my_obs, 0, id_quote_schedule], UpSuccess2, errorCB);
			}  
        });
    });

    function UpSuccess2() {
        console.log("Reunion actualizada correctamente ");
        $.mobile.changePage("#sales");
    }

    function querySuccessDisp_reschedulle(tx, results) {
        var len = results.rows.length;
        console.log( "Cantidad de citas "+ len);

        //if the schedule have quotes
        if (len > 0) {
            for (var i = 0; i < len;i++) {
                console.log( "Id Contacto = " + results.rows.item(i).id_contact + "   Date Reunion = "+ results.rows.item(i).date_reu_ini + " Hour End = "+ results.rows.item(i).date_reu_fin + " Efectiva = "+ results.rows.item(i).reu_efec + " Observaciones = "+ results.rows.item(i).obs);
            }
            db.transaction(queryavailable_re,errorCB);
        } else {
            console.log(
                    "Schedule is empty");
        }
    }

    function queryavailable_re(tx) {
        tx.executeSql("SELECT * FROM schedule WHERE julianday(date_reu_ini) BETWEEN julianday(" +
		"'" + fi_data_am + "')" + " AND julianday(" + "'" + fi_date_pm + "')" +
		"OR julianday(date_reu_fin) BETWEEN julianday(" + "'" + fi_data_am + "')" +
		" AND julianday(" + "'" + fi_date_pm + "')", [], queryavailableSuccess_re, errorCB);

    }

    function queryavailableSuccess_re(tx, results) {
        var len = results.rows.length;
        console.log("Concordancias " + len);

        if (len > 0) { 
            console.log("Cita Ya Asignada ");
            Dialog("La hora seleccionada ya se encuntra asignada a otra cita!", function(){}, "error");
            for (var i = 0; i < len; i++) {
                console.log("Id Contacto = " + results.rows.item(i).id_contact + "   Date Start Reunion = "+ results.rows.item(i).date_reu_ini + " Date Final Reunion = "+ results.rows.item(i).date_reu_fin + " Efectiva = "+ results.rows.item(i).reu_efec + " Observaciones = " + results.rows.item(i).obs);
            }
        } else {       	
        	executeSql('SELECT * FROM schedule WHERE id = ?', [id_quote_schedule], function sucessname (tx, results) {
                var len = results.rows.length;
                if (len > 0) {
     
                    for (var i = 0; i < len; i++) {
                    	  var idc =  results.rows.item(i).id_contact;
                    	  var prop =  results.rows.item(i).reu_efec;
                    	  var obs =  results.rows.item(i).obs;
                    	  var comp_id =  results.rows.item(i).company_id;
                    	  var enterp =  results.rows.item(i).enterprise_id;  
                    }
                    add_reschedule(idc, datenow, chk_status_reu_efect, obs, comp_id, enterp);
                }            
                else { 	
                }
            }, errorCB);
        }
    }
    
    
    $(document).on('pagebeforeshow', '#qoute', function(event) {	
    	event.preventDefault(); 
    	
    	if(Date.parse(date_meeting_selected) >= Date.parse(datenow)){
    		console.log("Botones Disponibles");
    		$("#div_btncalcel").css("display", "block");
     		$("#div_chk_reu_efect").css("display", "block");
     		$("#div_btnsave").css("display", "block");
     		$("#div_coords").css("display", "block");
    		 
    	}else{
    		console.log("Botones No Disponibles");
    		$("#div_btncalcel").css("display", "none");
    		$("#div_chk_reu_efect").css("display", "none");
    		$("#div_btnsave").css("display", "none");
    		$("#div_coords").css("display", "none");
    	}
    	  
    });
    
    $(document).on('pagebeforeshow', '#calendar', function(event) {
    	$(quotes).children().remove('div .cita');
    	if(control_display_quot == 1){
    		search_display_today();
    	}else{
    		search_display_for_date();
    	}
    	console.log("control_display_quot "+control_display_quot);
    });
    
    
    
     
       
    function add_reschedule(idc, datenow, prop, obs, comp_id, enterp){	
    	executeSql('INSERT INTO schedule (id_contact, creation_date, date_reu_ini, date_reu_fin, reu_efec, obs, company_id, enterprise_id, sincr, address, meeting_re) values (?,?,?,?,?,?,?,?,?,?,?);', 
    			[idc, datenow, fi_data_am, fi_date_pm, prop, obs, comp_id, enterp, 0, address_schedule, 1], insertSuccessReQuote, errorCB);
    }
    
    function insertSuccessReQuote() {
        console.log("Reunion Reagendada Correctamente");
        //	elimina la cita que previamente se re agendo   
        $.mobile.changePage("#index_co");
        executeSql('DELETE FROM schedule where id = ?;', [id_quote_schedule], DeleteSuccess, errorDelete);    
    } 
         
    function update_schedule_to_re(id_schedule){
    	executeSql('UPDATE schedule SET  meeting_re = ? WHERE id = ?', [id_schedule, 1], function sucessname (tx, results) {
    	console.log("Reunion Inicial cambiada a re agendada correctamente ");    
        }, errorCB);
    }
    
    function queryNameCompany() { 
        executeSql("SELECT * FROM contact WHERE id_server = ? ", [ID_CON], function sucessname (tx, results) {
        var len = results.rows.length;
 
        if (len > 0) {
            for (var i = 0; i < len; i++) {
                name_compsny_display = results.rows.item(i).name_company;				
                $('#name_company_quote').val(name_compsny_display);          
                console.log("Nombre de compaï¿½ia obtenido "+ results.rows.item(i).name_company);
            }
            query_last_obsertvation_quot(id_quote_schedule);    
        }
        //if not found any quote, is clear the before result
        else {
            console.error(
                    "No se encontro nombre de compania para este ID de contacto");
        }
    }, errorCB);
    }
    
    function query_last_obsertvation_quot(id_quote){
    	executeSql("SELECT obs, reu_efec FROM schedule WHERE id = ?", [id_quote], function sucessname (tx, results) {
            var len = results.rows.length;
            if (len > 0) {
 
                for (var i = 0; i < len; i++) {
                	var efect = results.rows.item(i).reu_efec;
                		if(efect == 1){	
                			//$('#chk_reu_efect').prop('checked', true);
                			$("#chk_reu_efect").attr("checked", "checked");
                		}
                    $('#obs_go_quote').val(results.rows.item(i).obs);   
                }
            }            
            else { 
            	console.warn("No se encontro observaciones para esta cita");
            }
        }, errorCB);
    }
  

    $('#search_calendar').click(function() {
    	//variable paracontrolar que mostrar al ingresar a la pagina de citas
    	control_display_quot = 2;
        //variables for display in each quote
        quotes = document.getElementById('calendar');
        f_ini2 = $("#datefrom").val() + " 00:00:00";
        f_fin2 = $("#dateto").val() + " 23:59:00";
        $(quotes).children().remove('div .cita');
         
        if(Date.parse(f_ini2) < Date.parse(f_fin2)){
        	search_display_for_date();
          
           //defina la accion sobre cada uno de los div correspondiente a las citas
            $(quotes).on("click", ".cita", function(e) {
                ID_CON = this.id;
                console.warn("DIV id de contacto "+ID_CON);
                id_quote_schedule = this.getAttribute("name");
                quotes = document.getElementById('calendar');
                $(quotes).children().remove('div .cita');
                get_address_meeting(id_quote_schedule);     
            });
        }else{
        	Dialog("La fecha de inicio debe ser menor a la fecha final!", function(){}, "info");
        }
   
    });
    
        
    
    function search_display_for_date(){
    	quotes = document.getElementById('calendar');
    	$(quotes).children().remove('div .cita');
    	executeSql("SELECT * FROM schedule WHERE sincr = ?", [0], function sucessname (tx, results) {
            var len = results.rows.length;
            
            console.log("Reuniones sin soncronizar "+len);
            if (len > 0) {     
                db.transaction(getQuotSI, errorCB);    
            }            
            db.transaction(getQuot, errorCB);        
        }, errorCB);
    }
    
     
     
    function get_address_meeting(id_meeting){
    	executeSql("SELECT date_reu_ini, address, reu_efec FROM schedule WHERE id = ?", [id_quote_schedule], function sucessname (tx, results) {
            var len = results.rows.length;
            if (len > 0) { 
            	for (var i = 0; i < len; i++) {
            		address_schedule = results.rows.item(i).address;
            		status_proposal = results.rows.item(i).reu_efec;
            		$('#address_meeting').val(address_schedule); 
            		date_meeting_selected = results.rows.item(i).date_reu_ini;
            		
            	}
            	queryNameCompany();
            	$.mobile.changePage("#qoute");
            }            
            db.transaction(getQuot, errorCB);        
        }, errorCB);
    }

       
    
    function getQuot(tx) {	    	
    	tx.executeSql("SELECT a.id, a.date_reu_ini, a.id_contact, b.name, b.id_server, a.address FROM schedule a" +
    	" LEFT JOIN contact b ON a.id_contact = b.id_server" +
    	" WHERE julianday(a.date_reu_ini) BETWEEN julianday(" + "'" + f_ini2 + "')" + 
    	" AND julianday(" + "'" + f_fin2 + "') AND a.sincr = ?   ORDER BY date_reu_ini DESC", [1], queryGetquoSucces, errorCB);	
    	}
    
     
    function getQuotDay(tx) {	
    	tx.executeSql("SELECT a.id, a.date_reu_ini, a.id_contact, b.name, b.id_server, a.address FROM schedule a" +
    	    	" LEFT JOIN contact b ON a.id_contact = b.id_server" +
    	    	" WHERE julianday(a.date_reu_ini) BETWEEN julianday(" + "'" + quotedaycurrent1 + "')" + 
    	    	" AND julianday(" + "'" + quotedaycurrent2 + "') AND a.sincr = ?  ORDER BY date_reu_ini DESC", [1], queryGetquoSucces, errorCB);     
    	}
        
    
    
    function getQuotSI(tx) {	    	
    	tx.executeSql("SELECT a.id, a.date_reu_ini, a.id_contact, b.name, b.id, a.address FROM schedule a" +
    	" LEFT JOIN contact b ON a.id_contact = b.id" +
    	" WHERE julianday(a.date_reu_ini) BETWEEN julianday(" + "'" + f_ini2 + "')" + 
    	" AND julianday(" + "'" + f_fin2 + "') AND a.sincr = ? ORDER BY date_reu_ini DESC", [0], queryGetquoSuccesSI, errorCB);	
    	}

  
	function getQuotDaySI(tx) {	
		tx.executeSql("SELECT a.id, a.date_reu_ini, a.id_contact, b.name, b.id, a.address FROM schedule a" +
		    	" LEFT JOIN contact b ON a.id_contact = b.id" +
		    	" WHERE julianday(a.date_reu_ini) BETWEEN julianday(" + "'" + quotedaycurrent1 + "')" + 
		    	" AND julianday(" + "'" + quotedaycurrent2 + "') AND a.sincr = ? ORDER BY date_reu_ini DESC", [0], queryGetquoSuccesSI, errorCB);	     
	}
	
	
  
 
function queryGetquoSucces(tx, results) {
    // n
     var len = results.rows.length;
     console.log("Reuniones encontradas =>: " + len);
     for (var i = 0; i < len; i++) {
 
         var myid = results.rows.item(i).id_server;
         var idquote = results.rows.item(i).id;
         var f = results.rows.item(i).date_reu_ini;
         var ff = f.substring(0, 16);
         var n = results.rows.item(i).name;
         address_schedule = results.rows.item(i).address;
         $(quotes).append(
              '<div class="cita" id=' + myid + ' name=' + idquote + '><p class="fecha">' + ff + '</p><p class="hora">' + n + '</p><p class="address">' + address_schedule + '</p></div>');  
     }
		 
 }


function queryGetquoSuccesSI(tx, results) {
     var len = results.rows.length;
     console.log("Reuniones encontradas NO sincronizadas =>: " + len);

     for (var i = 0; i < len; i++) {

         var myid = results.rows.item(i).id;
         var idquote = results.rows.item(i).id;
         var f = results.rows.item(i).date_reu_ini;
         var ff = f.substring(0, 16);
         var n = results.rows.item(i).name;
         var d = results.rows.item(i).address;  
         $(quotes).append(
              '<div class="cita" id=' + myid + ' name=' + idquote + '><p class="fecha">' + ff + '</p><p class="hora">' + n + '</p><p class="address">' + d + '</p></div>');  
     }
		 
 }


    $('#next_repor').click(function() {
        var selected = $("input:radio[name='radio1']:checked").val();

        switch (selected) {
            case '1':
                $.mobile.changePage("#rep_call_specify");
                break;

            case '2':
                $.mobile.changePage("#rep_specify_reu effective");
                break;

            case '3':
                $.mobile.changePage("#rep_effecsales");
                break;

            case '4':
                $.mobile.changePage("#rep_sales_dia");
                break;

            default:
                Dialog("Seleccione algun tipo de reporte!", function(){}, "info");
                break;
        }
 
    });

    $("#re_schedule").click(function() {
        if ($("#re_schedule").is(':checked')) {
            $("#div_re_schedule").css("display", "block");           
            $("#dv_save_and_send").css("display", "none");
        } else {
            $("#div_re_schedule").css("display", "none");
            $("#dv_save_and_send").css("display", "block");
        }
    });

    $("#chk_reu_efect").click(function() {
        if ($("#chk_reu_efect").is(':checked')) {
            chk_status_reu_efect = 1;            
        } else {
            chk_status_reu_efect = 0;            
        }
    });

    $("#add_newcompany").click(function() {
        if ($("#add_newcompany").is(':checked')) {
            $("#div_new_company").css("display", "block");
            person_judirica = 1;
            person_natural = 0;
        } else {
            $("#div_new_company").css("display", "none");
            person_judirica = 0;
            person_natural = 1;
            $('#list_companies option').filter(function() {
                return $(this).html() == "Seleccione una empresa";
            }).prop('selected', true);
            $('#list_companies').selectmenu("refresh", true);
        }
    });


    //event for contador of calls
    $('#flag').on('change', function() {
        var value = $('#flag').val();
        if (value == "on") {
        	get_date_last_call();
            count_call_exist = 1;
            $('#lbl_count_call').html(count_call_exist);
            db.transaction(updateCallCount, errorCB);
        } else {

        }
    });

    //display call for log
    $('#btn1').click(function() {
        db.transaction(QueryCallCount, errorCB);
    });
    //------------------------------insert table  calldia --------------------

    function QueryCallCount(tx) {
        tx.executeSql("SELECT * FROM calldia WHERE date_noti = ?", [datenow], function getCallSuccess(tx, results) {
            var len = results.rows.length;
            if (len == 0) {
                console.log("No hay registro de llamadas para esta fecha");
            } else {
                for (var i = 0; i < len; i++) {
                    console.log("Id: "+results.rows.item(i).id+" Llamadas realizadas el: " + results.rows.item(i).date_noti + "    Cantidad: " +results.rows.item(i).cntcall + "    Fecha Inicio Report: " + results.rows.item(i).dateini +"    Fecha comparate: " + results.rows.item(i).datacompara);
                    count_call_exist = results.rows.item(i).cntcall;
                    queryallregister_call();
                } 
            }
            $('#lbl_count_call').html(count_call_exist);
        }, errorCB);
    }
       
    function queryallregister_call(){
    	executeSql('SELECT * FROM calldia', [], function(tx, results) {
            var len = results.rows.length; 
            
            if (len > 0) { 
                console.log("Cantidad de registro de llamadas => " + len);
                for (var i = 0; i < len; i++) {
                	var fecha = results.rows.item(i).date_noti;
                    var cantidad = results.rows.item(i).cntcall;
                    var sincr = results.rows.item(i).sincr;
                    	console.log("Fecha: "+fecha+" cantidad: "+cantidad+" sincr: "+sincr);  
                }     
            } 
            else {
            	console.log("No Hay registro de llamadas que mostrar"); 
            }
        }, function(err) {
            console.error(" Error " + err);
        });
    }
  
    //------------------------------insert table  calldia --------------------																

    function updateCallCount(tx) {

        tx.executeSql("SELECT * FROM calldia WHERE date_noti = ?", [datenow], function getCallSuccess(tx, results) {
            var len = results.rows.length;
            var datainit = datenow + " 00:00:00"
            var data_comparate = proccessDate(datenow);

            //si la tabla esta vacia inserta el primer registro de llamada
            if (len == 0) {
                tx.executeSql("INSERT INTO calldia (date_noti, dateini, cntcall, datacompara, sincr) values (?,?,?,?,?);", [datenow, datainit, count_call_exist, data_comparate,0], SuccessCall, errorCB);
            }
            //si la tabla encuentra algun registro que coincida con la fecha, haceun update sobre la cantidad
            else {
                for (var i = 0; i < len; i++) {
                    count_call_exist = results.rows.item(i).cntcall + 1;
                    console.log("Fecha " + results.rows.item(i).date_noti + "  Cantdidad: " + results.rows.item(i).cntcall + "  Fecha inicio Repor: " + results.rows.item(i).dateini + "  Fecha comparate: " + results.rows.item(i).datacompara);
                    tx.executeSql("UPDATE calldia SET cntcall = ?, sincr = ? WHERE date_noti = ? ", [count_call_exist, 0, datenow], SuccessUpCall, errorCB);
                }
            } 
        }, errorCB);
    }

    function SuccessUpCall(tx, result) {
        var len = result.rows.length;
        console.log("Registro de llamadas actualizado localmente de manera satisfactoria");
        db.transaction(QueryCallCount, errorCB);
    }

    function SuccessCall(tx) {
        console.log("Register insert success in table calldia");
    }

//------------------------------Report concretized vs effective --------------------

    $('#btnreport2').click(function() {
        var date_;
        var concretadas;
        var efectivas;

        document.getElementById("dataTablerep2").innerHTML = "";
        var ff1 = $("#datefrom1").val();
        var ff2 = $("#dateto2").val();
        
        if(Date.parse(ff1) < Date.parse(ff2)){
        	 executeSql("SELECT creation_date,  COUNT(*) realizadas, SUM(reu_efec) AS efectivas FROM schedule a " + 
        				"WHERE julianday(date_reu_ini) >= julianday(" + "'" + ff1 + "')" + 
        				" AND julianday(date_reu_ini) <= julianday(" + "'" + ff2 + "')" + "GROUP BY creation_date", [], function Qsuccess(tx, results) {

        		            var len = results.rows.length;
        		            console.log("Reporte Concretadas Vs Efectivas");

        		            var tbl = document.getElementById('dataTablerep2');
        		            var lastRow2 = tbl.rows.length;
        		            var row2 = tbl.insertRow(lastRow2);

        		            var head1 = row2.insertCell(0);
        		            var head2 = row2.insertCell(1);
        		            var head3 = row2.insertCell(2);
        		            var head4 = row2.insertCell(3);

        		            head1.innerHTML = "Fecha";
        		            head2.innerHTML = "Concretada";
        		            head3.innerHTML = "Propuesta";
        		            head4.innerHTML = "Detalles";
 
        		            var lastRow = tbl.rows.length;

        		            for (var i = 0; i < len; i++) {
        		                var row1 = tbl.insertRow(lastRow);
        		                date_ = results.rows.item(i).creation_date;
        		                var Cell1 = row1.insertCell(0);
        		                var Cell2 = row1.insertCell(1);
        		                var Cell3 = row1.insertCell(2);
        		                var boton = document.createElement("input");
        		                boton.setAttribute('type', 'button');
        		                boton.setAttribute('name', "boton");
        		                boton.setAttribute('value', "Ver");
        		                boton.setAttribute('class', "btn_details");
        		                boton.setAttribute('id', date_);
        		                boton.onclick = function() {
        		                    id_date2 = this.id;
        		                    document.getElementById("dataTable_detailsrp2").innerHTML = "";
        		                    db.transaction(goDetails2repor, errorCB);
        		                };

        		                Cell1.innerHTML = results.rows.item(i).creation_date;
        		                Cell2.innerHTML = results.rows.item(i).realizadas;
        		                Cell3.innerHTML = results.rows.item(i).efectivas;
        		                row1.appendChild(boton);
        		            }

        		        }, errorCB);
        }else{
        	Dialog("La fecha inicial no puede ser mayor a la fecha final!", function(){}, "info");
        }

       

    });

    function proccessDate(date) {

        var elem = date.split('-');
        var anio = elem[0];
        var mes = elem[1];
        if (mes.length == 1) {
            mes = "0" + mes;
        }

        var dia = elem[2];
        if (dia.length == 1) {
            dia = "0" + dia;
        }
        return anio + "-" + mes + "-" + dia + " 00:00:00";
    }

    function goDetails2repor() {

        executeSql("SELECT a.id_contact, a.date_reu_ini, a.obs, b.name_company, b.name, b.phone2 FROM schedule a " +
		"LEFT JOIN contact b ON b.id_server = a.id_contact WHERE a.reu_efec = ? AND a.creation_date = ?", [1, id_date2], function getSuccess(tx, results) {

            var len = results.rows.length;

            var tbl2 = document.getElementById('dataTable_detailsrp2');
            document.getElementById("dataTable_detailsrp2").innerHTML = "";
            var lastRow2 = tbl2.rows.length;
            var row2 = tbl2.insertRow(lastRow2);
            var head_details1 = row2.insertCell(0);
            var head_details2 = row2.insertCell(1);
            var head_details3 = row2.insertCell(2);
            var head_details4 = row2.insertCell(3);
            var head_details5 = row2.insertCell(4);

            head_details1.innerHTML = "Empresa";
            head_details2.innerHTML = "Contacto";
            head_details3.innerHTML = "Telefono";
            head_details4.innerHTML = "Obs";
            head_details5.innerHTML = "Fecha Reunion";

            if (len == 0) {
                console.log("No hay detalles que mostrar");
                Dialog("No hay detalles que mostrar!", function(){}, "never");
            } else {
                for (var i = 0; i < len; i++) {
                    $.mobile.changePage("#details_rep_specefect");
                    var lastRow = tbl2.rows.length;
                    var row2 = tbl2.insertRow(lastRow);
                    var Cell1 = row2.insertCell(0);
                    var Cell2 = row2.insertCell(1);
                    var Cell3 = row2.insertCell(2);
                    var Cell4 = row2.insertCell(3);
                    var Cell5 = row2.insertCell(4);

                    Cell1.innerHTML = results.rows.item(i).name_company;
                    Cell2.innerHTML = results.rows.item(i).name;
                    Cell3.innerHTML = results.rows.item(i).phone2;
                    Cell4.innerHTML = results.rows.item(i).obs;
                    Cell5.innerHTML = results.rows.item(i).date_reu_ini;
                }
            }
        }, errorCB);
    }

    //event for delete quote
    $("#deletequote").click(function() {
    	confirmDialog("Realmente desea eliminar esta cita?", function(){
            executeSql('DELETE FROM schedule where id = ?;', [id_quote_schedule], DeleteSuccess, errorDelete);
            $.mobile.changePage("#index_co");
            $(quotes).children().remove('div .cita');
            meeting_delete(id_quote_schedule);  
        }); 
    });
     
      
    function meeting_delete(id_app_metting){
   	 executeSql("INSERT INTO auxdelete (id_app) VALUES(?);", [id_app_metting], function Success(tx, results) {
            console.log("id de agenda agregado correctamente a la tabla auxdelete");
            query_auxdelete();            
        }, function error(err) {
            console.error("Error agregado id de agenda a la tabla auxdelete " + err);
        });
   }

    function query_auxdelete(){
    	executeSql("SELECT * from auxdelete", [], function Success(tx, results) {
    		 var len = results.rows.length;  
    		 console.log("Registros de reuniones pendientes por eliminar "+len);
    		 if(len > 0){
    			 for (var i = 0; i < len; i++) {                    
  					console.log("ID_APP SCHEDULE => "+results.rows.item(i).id_app);						
                  }
    		 }else{
    			 console.log("No hay reuniones pendientes por eliminar");	
    		 }
    		 sincronize_delete_meeting(id_quote_schedule);   
        }, function error(err) {
            
        });
    }
    
    
    function DeleteSuccess() {
        console.log("Register Delete Success");
    }

    function errorDelete() {
        console.error("Error Delete Register");
    }
    
 
    function sincronize_delete_meeting(id_app){
    	 $.ajax({
             type: "POST",
            url: ubication + "synchronized_delete_server.php", 
             data: ({
            	 enterprise: enterprise_ID,
            	 name_seller: nameu_co,
            	 idapp: id_app,
            	 version: version_app,
				 timeout: 25000,
             }),
             async: true,
             success: function(datos) {
                 if(datos == 1){
                	 console.log("Reunion eliminada del servidor correctamente");
                 }
             },
             error: function(obj, error, objError) {
                 console.error("Error Eliminando Registro de reuni\u00f3n en el servidor");
             }
         });
    }

//------------------------------Report Graphics --------------------


//event for display report call <-> specify
    $('#btn_repor_call_spec').click(function() {
        document.getElementById("dataTable").innerHTML = "";

        var ff1 = $("#datefrom_rep_call_specify").val();
        var ff2 = $("#dateto_rep_call_specify").val();
        
        if(Date.parse(ff1) < Date.parse(ff2)){
            executeSql("select a.creation_date, b.cntcall, count(a.creation_date) contador from schedule a " +
            		"LEFT JOIN calldia b on  a.creation_date = b.date_noti WHERE julianday(a.date_reu_ini) >= julianday(" +
            		"'" + ff1 + "')" + " AND julianday(a.date_reu_ini) <= julianday(" + "'" + ff2 + "') group by creation_date", [], function a(tx, results) {

                        var len = results.rows.length;

                        var tbl = document.getElementById('dataTable');
                        var lastRow2 = tbl.rows.length;
                        var row2 = tbl.insertRow(lastRow2);
                        var head1 = row2.insertCell(0);
                        var head2 = row2.insertCell(1);
                        var head3 = row2.insertCell(2);
                        var head4 = row2.insertCell(3);

                        head1.innerHTML = "Fecha";
                        head2.innerHTML = "Llamadas";
                        head3.innerHTML = "Concretadas";
                        head4.innerHTML = "Detalles";

                        for (var i = 0; i < len; i++) {
                            console.log("Fecha : " + results.rows.item(i).creation_date);
                            console.log("Llamadas : " + results.rows.item(i).cntcall);
                            console.log("Concretadas : " + results.rows.item(i).contador);
                            id_date = results.rows.item(i).creation_date;

                            var lastRow = tbl.rows.length;

                            var row1 = tbl.insertRow(lastRow);

                            var Cell1 = row1.insertCell(0);
                            var Cell2 = row1.insertCell(1);
                            var Cell3 = row1.insertCell(2);
                            var boton = document.createElement("input");
                            boton.setAttribute('type', 'button');
                            boton.setAttribute('name', "boton");
                            boton.setAttribute('value', "Ver");
                            boton.setAttribute('class', "btn_details");
                            boton.setAttribute('id', id_date);
                            boton.onclick = function() {
                                id_date = this.id;
                                document.getElementById("dataTable_details").innerHTML = "";
                                db.transaction(goDetails, errorCB);
                            };

                            Cell1.innerHTML = results.rows.item(i).creation_date;
                            Cell2.innerHTML = results.rows.item(i).cntcall;
                            Cell3.innerHTML = results.rows.item(i).contador;
                            row1.appendChild(boton);
                        }
                    }, errorCB);
        }else{
        	 Dialog("La fecha inicial no puede ser mayor a la fecha final!", function(){}, "info");
        }
    });

    function goDetails() {
        executeSql("SELECT a.date_reu_ini, b.name, b.name_company, a.obs, b.phone2 FROM schedule a " +
		"LEFT JOIN contact b ON a.id_contact = b.id_server WHERE a.creation_date = ?", [id_date], function getCallSuccess(tx, results) {
            var len = results.rows.length;
            var tbl2 = document.getElementById('dataTable_details');
            var lastRow2 = tbl2.rows.length;
            var row2 = tbl2.insertRow(lastRow2);
            var head_details1 = row2.insertCell(0);
            var head_details2 = row2.insertCell(1);
            var head_details3 = row2.insertCell(2);
            var head_details4 = row2.insertCell(3);
            var head_details5 = row2.insertCell(4);

            head_details1.innerHTML = "Empresa";
            head_details2.innerHTML = "Contacto";
            head_details3.innerHTML = "Telefono";
            head_details4.innerHTML = "Fecha Llamada";
            head_details4.innerHTML = "Obs";
            head_details5.innerHTML = "Fecha Reunion";

            if (len == 0) {
                console.log("No hay detalles que mostrar");
            } else {
                for (var i = 0; i < len; i++) {
                    $.mobile.changePage("#details_rep_call_specify");

                    var lastRow = tbl2.rows.length;

                    var row2 = tbl2.insertRow(lastRow);

                    var Cell1 = row2.insertCell(0);
                    var Cell2 = row2.insertCell(1);
                    var Cell3 = row2.insertCell(2);
                    var Cell4 = row2.insertCell(3);
                    var Cell5 = row2.insertCell(4);

                    Cell1.innerHTML = results.rows.item(i).name_company;
                    Cell2.innerHTML = results.rows.item(i).name;
                    Cell3.innerHTML = results.rows.item(i).phone2;
                    Cell4.innerHTML = results.rows.item(i).obs;
                    Cell5.innerHTML = results.rows.item(i).date_reu_ini;
                }
            }
        }, errorCB);
    }
 
// event for set and display contact in page (sales)
    $(document).on('pagebeforeshow', '#sales', function() {
    	$("#div_register_sales").css("display", "block");
        db.transaction(queryContacts, errorCB);
    }); 
    

    function queryContacts(tx) {
        tx.executeSql('SELECT * FROM contact', [], querySuccessContact, errorCB);
    }

    function querySuccessContact(tx, results) {
        $('#list_cont_sales option[value!=1]').remove()
        var len = results.rows.length;
        var listcontsales = document.getElementById('list_cont_sales');
        console.log("Number Contacts : " + len);
        for (var i = 0; i < len; i++) {
            console.log("ID = " + results.rows.item(i).id +" Company = "+ results.rows.item(i).name_company +" User =  "+ results.rows.item(i).name +" Role =  "+ results.rows.item(i).role +" Phone Fixe =  "+ results.rows.item(i).phone1 +" Phone Movil =  "+ results.rows.item(i).phone2);

            var id_contact = results.rows.item(i).id;
            var comp = results.rows.item(i).name_company;
            var user = results.rows.item(i).name;
            var pso = results.rows.item(i).role;
            var ph1 = results.rows.item(i).phone1;
            var ph2 = results.rows.item(i).phone2;

            $(listcontsales).append('<option id=' + id_contact + '>' + user+ '</option>');
        }
        $(listcontsales).selectmenu().selectmenu('refresh', true);
        
      //si se selecciona guardar y vender, carga los datos del contacto de esa cita    	
    	if(status_pass_to_sale==1){
    		getdata_schedulle(id_quote_schedule);
    	}
    }
    
    
    function getdata_schedulle(id_quot){
    	executeSql("SELECT * FROM schedule WHERE id = ?", [id_quot], function Success(tx, results) {
            var len = results.rows.length; 

            if (len > 0) {
            	for (var i = 0; i < len; i++) {
                console.log("Consultando los datos de la reuni\u00f3n...");
                var id_contact = results.rows.item(i).id_contact;
                console.log("ID del contacto en la reuni\u00f3n => "+id_contact);
                getname_contact(id_contact);
            	}
            } else {
                console.warn("no hay datos de la reuni\u00f3n con ID "+id_quot);  
            }
        }, function error(err) {
                console.error("Error consultando datos de la cita con id " + id_quot);
        });
    }
    
    function getname_contact(id){
    	
    	executeSql("SELECT name, name_company, phone1, phone2 FROM contact WHERE id_server = ?", [id], function Success(tx, results) {
            var len = results.rows.length;
            if (len > 0) { 	  
            	for (var i = 0; i < len; i++) {
	               
            		$('#list_cont_sales option').filter(function() {
                        return $(this).html() == results.rows.item(i).name;
                    }).prop('selected', true);
                    $('#list_cont_sales').selectmenu("refresh", true);
                    $('#name_company').val(results.rows.item(i).name_company);
                    $('#tel_fix_sales').val(results.rows.item(i).phone1);
                    $('#tel_cel_sales').val(results.rows.item(i).phone2);
            	}
            } else {
                console.warn("No se encontraron los datos de la contacto con ID..."+id);  
            }
        }, function error(err) {
            console.error("Error consultando datos del contacto con id " + id);
        });	
    }

    $("#list_cont_sales").change(function() {
    	idContactSales = $(this).children(":selected").attr("id");
        executeSql("select name_company, phone1, phone2 FROM contact WHERE id = ?", [idContactSales], function ab(tx, results) {
            var len = results.rows.length;

            for (var i = 0; i < len; i++) {
                $('#name_company').val(results.rows.item(i).name_company);
                $('#tel_fix_sales').val(results.rows.item(i).phone1);
                $('#tel_cel_sales').val(results.rows.item(i).phone2);
            }
        }, errorCB);
    });
    
    
  function getIdCompany(name_company, valuesale, observ_sales, date_reg){ 
    executeSql("SELECT id from company where name =?",[name_company], function Success(tx, results) {				
			var len = results.rows.length;  
			if(len > 0){
				for (var i = 0; i < len; i++) {
					var id_compan = results.rows.item(i).id; 
	
    confirmDialog(" Desea Registrar esta venta? ", function(){
			            executeSql("INSERT INTO sales (id_contact, value_sale, date_sale, creation_date_sale, obs, company_id, enterprise_id, sincr) values (?,?,?,?,?,?,?,?)", 
						[idContactSales, valuesale, date_reg, datenow ,observ_sales, id_compan, enterprise_ID,0], function abc(tx, results) {
			                console.log("Nueva venta ingresada");
			                $.mobile.changePage("#index_co");
			            }, errorCB)
			        });
			        	$("#div_register_sales").css("display", "block");
			        
	            } 
			}else{
				//si es una persona natural, que es igual a id de company igial a cero
				confirmDialog(" Desea Registrar esta venta? ", function(){ 
		            executeSql("INSERT INTO sales (id_contact, value_sale, date_sale, creation_date_sale, obs, company_id, enterprise_id, sincr) values (?,?,?,?,?,?,?,?)", 
					[idContactSales, valuesale, date_reg, datenow ,observ_sales, 0, enterprise_ID,0], function abc(tx, results) {
		                console.log("Nueva venta ingresada");
		                $.mobile.changePage("#index_co");
		            }, errorCB)
		        });
				$("#div_register_sales").css("display", "block");
			}
            
        }, errorCB);	
   
    
    }


    $('#register_sales').click(function() {
    	$("#div_register_sales").css("display", "none");
        var valuesale = $("#value_sales").val();
        var observ_sales = $("#obs_sales").val();
        var date_reg = proccessDate(datenow); 
        var name_company = $("#name_company").val(); 
        //obtenemos el id del contacto
        idContactSales = $('#list_cont_sales option:selected').attr('id');
        getIdCompany(name_company, valuesale, observ_sales, date_reg);
    });

    var dat_btnsales; 
    
    // Reporte propuestas vs Ventas
    $("#btn_repefec_sales").click(function() {
        document.getElementById("dataTablerep3").innerHTML = "";
        var cant;
        var ff1 = $("#dateeffect_sales1").val();
        var ff2 = $("#dateeffect_sales2").val();
        
  
        if(Date.parse(ff1) < Date.parse(ff2)){
        	executeSql("SELECT DATE(date_sale) AS FECHA, COUNT(id) AS VENTAS, " +
    				"  		(SELECT SUM(reu_efec)"+
    				"  		  FROM schedule"+
    				"  		  WHERE DATE(date_reu_ini) = DATE(date_sale)) AS EFECTIVAS " +
    				"  FROM sales"+
                    "  WHERE date_sale"+
                    "  BETWEEN DATE(" + "'" + ff1 + "')" +
                    "  AND DATE(" + "'" + ff2 + "')" +
                    "  GROUP BY date_sale ", [], function getSuccess2(tx, results) {
            	
    			var len = results.rows.length;
    			var tbl = document.getElementById('dataTablerep3');
                var lastRow2 = tbl.rows.length;
                var row2 = tbl.insertRow(lastRow2);
                var head1 = row2.insertCell(0);
                var head2 = row2.insertCell(1);
                var head3 = row2.insertCell(2);
                var head4 = row2.insertCell(3);

                head1.innerHTML = "Fecha Reportada";
                head2.innerHTML = "Efectivas";
                head3.innerHTML = "Ventas";
                head4.innerHTML = "Detalles";
                
    		
                for (var i = 0; i < len; i++) {
                	var date_sale = results.rows.item(i).FECHA;
                	var cant_sales = results.rows.item(i).VENTAS;
                	var cant_efect = results.rows.item(i).EFECTIVAS;
    				
                	 var lastRow = tbl.rows.length;
                     var row1 = tbl.insertRow(lastRow);
                     var Cell1 = row1.insertCell(0);
                     var Cell2 = row1.insertCell(1);
                     var Cell3 = row1.insertCell(2);
     
                     var boton = document.createElement("input");
                     boton.setAttribute('type', 'button');
                     boton.setAttribute('name', "boton");
                     boton.setAttribute('value', "Ver");
                     boton.setAttribute('class', "btn_details");
                     boton.setAttribute('id', date_sale); 				

                     boton.onclick = function() {
                         dat_btnsales = this.id;                 
                         document.getElementById("Tablesaledetailrep").innerHTML = "";
                         db.transaction(goDetailsales, errorCB);
                     };

                     //var datedis = results.rows.item(i).date_sale; 
                     Cell1.innerHTML = date_sale;
                     Cell2.innerHTML = cant_efect;
                     Cell3.innerHTML = cant_sales;
                     row1.appendChild(boton);	
                }
            }, errorCB);
        }else{
        	Dialog("La fecha de inicio no puede ser mayor a la fecha final!", function(){}, "info");
        }  
	});	
		
  
    function goDetailsales() {
    	 executeSql("SELECT a.date_sale, a.value_sale, a.obs,  b.name, b.name_company, b.phone2 FROM sales a " + 
        		"LEFT JOIN contact b ON a.id_contact = b.id WHERE a.creation_date_sale = ?", [dat_btnsales], function getCallSuccess(tx, results) {    		 
    		 var len = results.rows.length;   		
             var tbl2 = document.getElementById('Tablesaledetailrep');
             var lastRow2 = tbl2.rows.length;
             var row2 = tbl2.insertRow(lastRow2);
             var head_details1 = row2.insertCell(0);
             var head_details2 = row2.insertCell(1);
             var head_details3 = row2.insertCell(2);
             var head_details4 = row2.insertCell(3);
             var head_details5 = row2.insertCell(4);
             
             
             head_details1.innerHTML = "Empresa";
             head_details2.innerHTML = "Contacto";
             head_details3.innerHTML = "Fecha";
             head_details4.innerHTML = "Observ";
             head_details5.innerHTML = "Total";
            
             
             if (len == 0) {
                 console.log("No hay detalles que mostrar");
             } else {
            	 
            	 $.mobile.changePage("#repdetail_effecsales");
            	 for (var i = 0; i < len; i++) {

            	 var lastRow = tbl2.rows.length;

                 var row2 = tbl2.insertRow(lastRow);
                 var Cell1 = row2.insertCell(0);
                 var Cell2 = row2.insertCell(1);
                 var Cell3 = row2.insertCell(2);
                 var Cell4 = row2.insertCell(3);
                 var Cell5 = row2.insertCell(4);
                 
                 
                 var datedis = results.rows.item(i).date_sale;
                 var cant = datedis.length;
                 var new_datedis = datedis.substring(0, cant - 8);
                 
                 Cell1.innerHTML = results.rows.item(i).name_company;
                 Cell2.innerHTML = results.rows.item(i).name;
                 Cell3.innerHTML = new_datedis;
                 Cell4.innerHTML = results.rows.item(i).obs;
                 Cell5.innerHTML = results.rows.item(i).value_sale;
             } 
    	 } 
        }, errorCB);
    }


    var dd;

    $("#btnrep_salesdia").click(function() {
        document.getElementById("dataTablerep4").innerHTML = "";

        d1 = $("#daterep_saledia1").val();
        d2 = $("#daterep_saledia2").val(); 
        
        if(Date.parse(d1) < Date.parse(d2)){
        	executeSql("SELECT *, SUM(a.value_sale) AS suma FROM sales a " + 
        			" WHERE julianday(a.date_sale) >= julianday(" + "'" + d1 + "')" + 
        			" AND julianday(a.date_sale) <= julianday(" + "'" + d2 + "')" + 
        			" GROUP BY a.date_sale", [], function Qsuccess(tx, results) {

        	            var len = results.rows.length;
        	            var tbl = document.getElementById('dataTablerep4');
        	            var lastRow2 = tbl.rows.length;
        	            var row2 = tbl.insertRow(lastRow2);
        	            var head1 = row2.insertCell(0);
        	            var head2 = row2.insertCell(1);
        	            var head3 = row2.insertCell(2);

        	            head1.innerHTML = "Fecha";
        	            head2.innerHTML = "Total";
        	            head3.innerHTML = "Detalles";     

        	            for (var i = 0; i < len; i++) {

        	                var lastRow = tbl.rows.length;
        	                var row1 = tbl.insertRow(lastRow);

        	                var Cell1 = row1.insertCell(0);
        	                var Cell2 = row1.insertCell(1);

        	                var boton = document.createElement("input");
        	                boton.setAttribute('type', 'button');
        	                boton.setAttribute('name', "boton");
        	                boton.setAttribute('value', "Ver");
        	                boton.setAttribute('class', "btn_details");
        	                boton.setAttribute('id', results.rows.item(i).date_sale);
        	                boton.onclick = function() {
        	                    dd = this.id;
        	                    document.getElementById("dataTabledetailsalesdia").innerHTML = "";
        	                    db.transaction(goDetailsalesdia, errorCB);
        	                };

        	                var datedis = results.rows.item(i).date_sale;
        	                var cant = datedis.length;
        	                var new_datedis = datedis.substring(0, cant - 8);

        	                Cell1.innerHTML = new_datedis;
        	                Cell2.innerHTML = results.rows.item(i).suma;
        	                row1.appendChild(boton);
        	            }

        	        }, errorCB);
        }else{
        	Dialog("La fecha inicial no puede ser mayor a la fecha final!", function(){}, "info");
        }

        
    });

    function goDetailsalesdia() {
        executeSql("SELECT a.date_sale, a.value_sale, b.name_company FROM sales a " + 
		" LEFT JOIN contact b ON a.id_contact = b.id " +
		" WHERE date_sale = ?", [dd], function getCallSuccess(tx, results) {

            var len = results.rows.length;
            var tbl2 = document.getElementById('dataTabledetailsalesdia');
            var lastRow2 = tbl2.rows.length;

            var row2 = tbl2.insertRow(lastRow2);
            var head_details1 = row2.insertCell(0);
            var head_details2 = row2.insertCell(1);
            var head_details3 = row2.insertCell(2);

            head_details1.innerHTML = "Fecha";
            head_details2.innerHTML = "Empresa";
            head_details3.innerHTML = "Valor Venta";

            if (len == 0) {
                console.log("No hay detalles que mostrar");
            } else {
                for (var i = 0; i < len; i++) {

                    $.mobile.changePage("#detailsales_dia");

                    var lastRow = tbl2.rows.length;

                    var row2 = tbl2.insertRow(lastRow);

                    var Cell1 = row2.insertCell(0);
                    var Cell2 = row2.insertCell(1);
                    var Cell3 = row2.insertCell(2);

                    var datedis = results.rows.item(i).date_sale;
                    var cant = datedis.length;
                    var new_datedis = datedis.substring(0, cant - 8);

                    Cell1.innerHTML = new_datedis;
                    Cell2.innerHTML = results.rows.item(i).name_company;
                    Cell3.innerHTML = results.rows.item(i).value_sale;
                }
            }
        }, errorCB);

        executeSql("SELECT *, b.name_company,  SUM(a.value_sale) AS suma FROM sales a " + 
		"LEFT JOIN contact b ON a.id_contact = b.id " + " GROUP BY b.name_company", [], function Qsuccess(tx, results) {

            var len = results.rows.length
            document.getElementById("datatablecompany").innerHTML = "";
            var tbl2 = document.getElementById('datatablecompany');
            var lastRow2 = tbl2.rows.length;
            var row2 = tbl2.insertRow(lastRow2);

            var head_details1 = row2.insertCell(0);
            var head_details2 = row2.insertCell(1);

            head_details1.innerHTML = "Nombre Empresa";
            head_details2.innerHTML = "Total";

            for (var i = 0; i < len; i++) {
                var lastRow = tbl2.rows.length;
                var row2 = tbl2.insertRow(lastRow);
                var Cell1 = row2.insertCell(0);
                var Cell2 = row2.insertCell(1);

                Cell1.innerHTML = results.rows.item(i).name_company;
                Cell2.innerHTML = results.rows.item(i).suma;
            }

        }, errorCB);

    }
    
 
 
    //event for set coords of user
    $('#flip_location').on('change', function() {
        var value = $('#flip_location').val();
        if (value == "on") {
        	//db.transaction(Sendlocation, errorCB);
        	GetGeoLocation ();
        } 
    });
    
    
     
    function  GetGeoLocation () {
    	  var options =  { maximumAge: 3000, timeout: 15000, enableHighAccuracy: true };
    	  navigator.geolocation.getCurrentPosition(ShowPosition, ShowError, options);
    	}
    
    function ShowPosition(position) {       
        var lat = position.coords.latitude;
        var lon = position.coords.longitude;
         
        
        $.ajax({
            type: "POST",
            url: ubication + "set_geolocation.php",
            data: ({           	
                latitude: lat,
                longitude: lon,
                id_app: id_quote_schedule,
                name_seller: nameu_co, 
                enterprise_id: enterprise_ID,
				timeout: 25000, 
            }),  
            async: true,
            success: function(datos) {
                console.log(datos);
            },
            error: function(obj, error, objError) {
                console.error("Error sending coords of device");
            }
        });     
    }
    
    function ShowError(error) {
    	   console.warn("Errorcode: "    + error.code    +
    	         "Errormessage: "+ error.message );
    	}
} //close ondeviceready 4834

